Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Returned value not expected – closures

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();

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading