2

I have question, related to JavaScript Scope:-

var a = 10;
function show() {
   alert(a);
   var a = 20;
   alert(a);
}
show();
alert(a);

Above gives me output as "undefined" 20 10

I understood last two output, but why undefined in first alert, I interpreted result as 10, 20, 10 because its a script, it will run line by line, so when first alert will encounter it will treat a global and alert me with 10, but all this theory goes wrong.

Could you please explain me, whats the actual theory and where I am going wrong

thanks

2

2 Answers 2

6

Hoisting: A Problem with Scattered vars

JavaScript enables you to have multiple var statements anywhere in a function, and they all act as if the variables were declared at the top of the function. This behavior is known as hoisting. This can lead to logical errors when you use a variable and then you declare it further in the function. For JavaScript, as long as a variable is in the same scope (same function), it’s considered declared, even when it’s used before the var declaration. Take a look at this example:

myname = "global"; // global variable
function func() {
  alert(myname); // "undefined"
  var myname = "local";
  alert(myname); // "local"
}
func();

In this example, you might expect that the first alert() will prompt “global” and the second will prompt “local.” It’s a reasonable expectation because, at the time of the first alert, myname was not declared and therefore the function should probably “see” the global myname. But that’s not how it works. The first alert will say “undefined” because myname is considered declared as a local variable to the function. (Although the declaration comes after.) All the variable declarations get hoisted to the top of the function. Therefore to avoid this type of confusion, it’s best to declare upfront all variables you intend to use.

The preceding code snippet will behave as if it were implemented like so:

myname = "global"; // global variable
function func() {
  var myname; // same as -> var myname = undefined;
  alert(myname); // "undefined"
  myname = "local";
  alert(myname); // "local"
}
func();
Sign up to request clarification or add additional context in comments.

1 Comment

do you know why this kind of behavior is developed in a language, I mean when language itself support declaring variable any where not like C, still, it gives an error.
1

Lookup variable hoisting, the variable definition get hoisted initialization not.

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.