Home > Net >  Returned value not expected - closures
Returned value not expected - closures

Time:05-04

I don't understand why it returns 0, it is supposed to increment by 1, is there something I don't know about closures?

 let i = 0;
    const getRenderValue = function() {

      return i  ;
    };
    const Component = function() {
      let hello = getRenderValue();
      console.log(hello); // return 0, expected value 1
    };
    Component();

CodePudding user response:

Your closure does increment the value of i by one. If you did console.log(i); instead of console.log(hello);, you'd be seeing 1 on screen as expected.

Your closure however returns the value of i prior to the increment as it returns i : It is a property of the postfix increment i that it returns i before and not after the increment. Use the prefix increment i if you want to return the changed value.

  • Related