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"]
SOHAIB NISAR
  • 81
  • 1
  • 3
  • Move `let array = ['x', 'r', 'r'];` outside the function. Your current code is recreating the array anew each time the function runs. –  Dec 22 '19 at 09:56
  • how can i do same thing in react using state – SOHAIB NISAR Dec 22 '19 at 10:01
  • https://stackoverflow.com/questions/26253351/correct-modification-of-state-arrays-in-reactjs –  Dec 22 '19 at 10:02

1 Answers1

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.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320