Search code examples
javascripttypescriptfor-loopvariablesvariable-assignment

Variable 'value' is used before being assigned


My code:

function test() {
  let value: number;

  for (let i = 0; i < 10; i++) {
    value = i;
    console.log(value);
  }

  return value;
}

test();

And got this:

Variable 'value' is used before being assigned

I found this very odd, as I had seen other similar problems that either used a callback or a Promise or some other asynchronous method, while I used just a synchronous for loop.

---------------------------------- Some update ------------------------

function test() {
  let value: number;

  for (let i = 0; i < 100; i++) {
    // a() is very expensive and with some effects
    const result = a(i)

    if(i===99) {
      value = result
    }

  }

  return value;
}


Solution

  • Use the non-null assertion operator to ensure that "its operand is non-null and non-undefined in contexts where the type checker is unable to conclude that fact."

    function test() {
      let value!: number;
    
      for (let i = 0; i < 10; i++) {
        value = i;
        console.log(value);
      }
    
      return value;
    }
    
    test();
    

    Result