Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
My question is regarding the below code:
var z='1'; (function(){ y='2'; console.log(z+y); // '12' })(); console.log(z+y); // '12'
How come 'y' is accessible outside the function's scope?
global
var
var z='1'; (function(){ var y='2'; console.log(z+y); })(); console.log(z+y);
You declared y like this y='2'; By not putting the var keyword in front of it, the variable automatically becomes global.
y
y='2';
Add a comment
Key word without a var in front of it is declared as global variable.
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
global...variables declared withoutvarkeyword are global variables..var z='1'; (function(){ var y='2'; console.log(z+y); })(); console.log(z+y);will throw error Uncaught ReferenceError: y is not defined