JavaScript scope
I hope to use the most correct terminology that I know at the moment, and I also know that this is not entirely correct. I am not a javascript guru, but this question you are asking about is related to the JavaScript realm . You can find many articles on this topic, as well as some Q & A on SO too, as I found with examples.
Step by step
I will try to play line by line what your snipnet does. Please comment if you notice the wrong term somewhere, I like to study always, I can: D
line 1
var doB = function() { return a+1};
means
Save the variable with the name "doB" in the current area, assign its contents to an anonymous function.
So...
a now doesn't matter.
line 2
var b = a+1;
means
Save the variable with the name b in the current area, add its contents to new Integer(1) in addition to the variable a .
So...
At this point, a is undefined because it is not declared in the current scope, none of the available scopes are available. The operation undefined + a is equal to NaN . a assigned to NaN as a value.
line 3
var a = 3;
means
Save the variable with the name a in the current area, assign its contents to new Integer(3)
So...
Now we have a variable a that stores an integer.
line 4
console.log(b);
The conclusion is NaN , because b is actually NaN .
line 5
console.log( doB() );
means
Call the console.log function with the value returned by the doB function doB with no arguments as the first argument.
So...
doB is called and returns: a + 1
What means
new Integer(1) in addition to the variable a . a does not exist in the local function region, but exists in the region accessible inside the function. The value is taken from there, which is actually 3 . Console Exits 4 .