2

I am currently trying to learn Javascript and understand that functions are one of the most important aspects of the language but I have to say Im finding it very hard to understand them especially when different parameters are being used here there and everywhere.

I have been looking at this code which I read in another stack overflow post regarding closure and cant understand how 16 is alerted, I have used console.log to work out what value is being used at each point and seem to get a total of 17, could someone possibly explain?

function foo(x) {
 // console.log(x); = 2    
 var tmp = 3;
 return function (y) {
  // console.log(y); = 10
  alert(x + y + (++tmp));
  // console.log(++tmp); = 5?
 }
}
var bar = foo(2);
bar(10);

If anyone can offer any wisdom about functions that might make things start to make sense for me it would be really appreciated.

Kyle

3 Answers 3

5

The alert() command really pops up 16.

++tmp is preincrement statement - first, it increments the value (from 3 to 4) and then continues with execution of the line.

So 2 + 10 + 4 is passed to the alert().

The console.log(++tmp) below the alert logs 5, because the tmp variable is incremented again, from 4 to 5.

Sign up to request clarification or add additional context in comments.

Comments

0

Try to log

console.log(tmp);

Instead of

console.log(++tmp);

Comments

0

foo(2) initializes tmp to 3 and x to 2 within the scope of the returned function. bar(10) then adds 2, 10, and the result of incremented tmp (which went from 3 to 4 before being added to x and y).

so the alerted value will be the sum of 2 + 10 + 4.. 16.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.