0

I'm using reactjs.

I have a series of divs that are created that represent a employee's availability. When clicked, they will display the number. However, they all alert the number 25 instead of their number.

for (
      var i = state.availability[day][0];
      i <= state.availability[day][1];
      i++
    ) {
      tempdaySlot.push(
        <div
          key={"ena:" + TimeConverter(i)}
          style={LocalStyles.daySlot}
          onClick={() => alert(i)}
        >
          {TimeConverter(i)}
        </div>
      );
    }

state.availability is a two dimensional array that holds a number between 1-24 that represents someone's availability (ex [9-17])

TimeConverter is a function that converts a 24 hour type number to the usual 12 hour format (17 = "5 pm")

tempdaySlot is just a temporary array before I put it into a state variable

Marnie Rodriguez
  • 431
  • 2
  • 8
  • 22

3 Answers3

3

Use let i instead of var i. var hoists variable to the parent scope, let creates block scope.

givehug
  • 1,863
  • 1
  • 14
  • 19
1

Tl;dr declare i using let, not var

The var keyword creates variables with function scope. However, when you create a closure (like your onClick function), the lexical environment is captured by reference. When you call that onClick function later, it gets the current value of i (which is 25, since that's where the loop stopped), not the value of i when you created the function.

The let keyword creates i with traditional scoping, so in effect a new i is created on each iteration of the loop which solves this problem.

See What's the difference between using "let" and "var"? for more.

Elan Hamburger
  • 2,137
  • 10
  • 14
1

this is a hoisting issue, because you defined the i using var it will be hoisted to the top of the function body so the last value which is 25 will be the only thing stored in that variable and since the variable isn't destroyed because it's hoisted it will only show the latest value.

just use let instead of var its a good practice to use let and const instead of var now so try getting used it, it will save you a lot of headaches.

Ali Hassan
  • 198
  • 1
  • 11