Why is 100 being logged here instead of 101?
function myFunction() {
var i=100;
function f() {
return i++;
}
return f();
};
var X = myFunction();
console.log(X);
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because
f()returns the value ofibefore it is incremented. Use pre-increment (++i) if you want the value after it is incremented.Also, it’s a bit odd to declare
f()for no other purpose than to immediately call it. I think what you intended was to return a function that incrementsiand returns the new value each time it is called. To achieve this, simply return the function, then callconsole.log(X())to invokef()and log the incremented value: