styler
styler

Reputation: 16491

Javascript functions question, could someone possibly help explain?

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

Upvotes: 2

Views: 110

Answers (3)

Kon
Kon

Reputation: 27441

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.

Upvotes: 0

ChristopheCVB
ChristopheCVB

Reputation: 7315

Try to log

console.log(tmp);

Instead of

console.log(++tmp);

Upvotes: 0

Ondřej Mirtes
Ondřej Mirtes

Reputation: 5616

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.

Upvotes: 5

Related Questions