0

For example, I have a toggle button, which would show the current selected element, and would show next element when it is clicked, and it can loop back to first element. I have 2 ways to store the current selected element:

1.Use a variable i to store the selected index:

<button id="b" onclick="onButtonPressed()"/>
<button onclick="onSubmit()">Submit</button>
<script>
  let i=0;
  let arr=['Red','Yellow','Green','Blue'];
  function onButtonPressed(){
    i=i++%arr.length;
    document.getElementById('b').innerHTML=arr[i];
  }
  document.getElementById('b').innerHTML=arr[i]

  function onSubmit(){
    //call url:xxxxx.com/submit?value=arr[i]
  }
</script>

2.Use first position as the selected element

<button id="b" onclick="onButtonPressed()"/>
<button onclick="onSubmit()">Submit</button>
<script>
  let arr=['Red','Yellow','Green','Blue'];
  function onButtonPressed(){
    arr.push(arr.shift());
    document.getElementById('b').innerHTML=arr[0];
  }
  document.getElementById('b').innerHTML=arr[0]

  function onSubmit(){
    //call url:xxxxx.com/submit?value=arr[0]
  }
</script>

If both method can be used, and I don't care the initial position of elements, which one should I use?

1 Answer 1

2

Well your first method would be more efficient, though the "cost" of shifting and pushing an element of the array for all intents and purposes is not worth even taking into consideration.

The second method would be more memory-efficient, though again, the "cost" of holding the value of i in memory is not even worth taking into consideration.

So ultimately it comes down to readability. Which is more readable? I would say the second, as there is less clutter and it is a slightly more "elegant" solution, but it is highly subjective.

Ultimately, make your own choice here. Weigh your code in terms of efficiency and memory usage and readability, and then be confident in your decision. Good luck!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.