0

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?

3
  • 1
    Because it is global...variables declared without var keyword 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 Commented Feb 29, 2016 at 10:17
  • 1
    with "var" like var z='1' is local and without "var" like y='2' is global. Commented Feb 29, 2016 at 10:19
  • 1
    y is global variable..if u want to prevent then u should use var Commented Feb 29, 2016 at 10:20

2 Answers 2

3

You declared y like this y='2'; By not putting the var keyword in front of it, the variable automatically becomes global.

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

Comments

0

Key word without a var in front of it is declared as global variable.

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.