0

I have a array and i want to toggle its value on 0 index on button click between 'x' and 'a' but this is not working.I can not understand what i am doing wrong i am new in JavaScript.

function toggle() {
    let array = ['x', 'r', 'r'];
    let i = 0;
    if (array[i] == 'a') {
        array[i] = 'x';
    }
    else {
        array[i] = 'a';
    }

    console.log(array)
}
<button onclick='toggle()'>Toggle</button>

expected output

["a", "r", "a"]
["x", "r", "a"]
["a", "r", "a"]
["x", "r", "a"]

but got

["a", "r", "a"]
["a", "r", "a"]
["a", "r", "a"]
["a", "r", "a"]
3
  • Move let array = ['x', 'r', 'r']; outside the function. Your current code is recreating the array anew each time the function runs. Commented Dec 22, 2019 at 9:56
  • how can i do same thing in react using state Commented Dec 22, 2019 at 10:01
  • stackoverflow.com/questions/26253351/… Commented Dec 22, 2019 at 10:02

1 Answer 1

2

Declare the array outside of toggle, so that changes to it can be observed over multiple calls of toggle:

const array = ['x', 'r', 'r'];

function toggle() {
  let i = 0;
  if (array[i] == 'a') {
    array[i] = 'x';
  } else {
    array[i] = 'a';
  }

  console.log(array)
}
<button onclick='toggle()'>Toggle</button>

Otherwise, you'll be creating a new array containing ['x', 'r', 'r'] on every call, so it'll change the first element from an x to an x and log ["a", "r", "a"] every time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.