-1

Case 1: The following Code alerts 10 as it should:

var globalId='10';  
function check(){  
    alert(globalId);  
}  
check();

Case 2: But this next code alerts undefined:

var globalId='10';  
function check(){  
    alert(globalId); 
    var globalId; 
}  
check();

For Case 2 the solution is :

var globalId='10';  
function check(){  
    var globalId; /**moved to top of the function due to hoisting and has an initial value of undefined. Hence, alert(globalId) return undefined. **/

alert(globalId); //undefined
var globalId; 
}  
check();

My question is now, how does in Case 1 globalId has the value of 10 ?

Rajesh
  • 24,354
  • 5
  • 48
  • 79
Naruto
  • 1
  • 1

3 Answers3

1

Never. In JavaScript, variables declared in the current functional scope always take precedence over variables declared in the outer scope.

In your second example,

var globalId='10';  
function check(){  
    alert(globalId); 
    var globalId; 
}  
check();

The interpreter automatically moves your var globalId declaration to the top for you, which results in:

var globalId='10';  
function check(){  
    var globalId;
    alert(globalId);
}  
check();

and that's why it's showing undefined.

Derek 朕會功夫
  • 92,235
  • 44
  • 185
  • 247
  • I don't think the interpreter moves anything. When creating an execution context, function and variable declarations are processed first, then code is executed, hence why declared variables and functions exist prior to code execution. I dislike the term "hoisting" because it infers that code is moved. – RobG Nov 10 '17 at 06:24
  • @RobG The term "moved" is used because it's easier to understand. You are absolutely correct that the line isn't physically moved (you are RobG after all ;) ) but all variable declarations will be performed before anything else in their context. – Derek 朕會功夫 Nov 10 '17 at 06:36
0

My question is now, how does in Case 1 globalId has the value of 10?

Because

  • In JavaScript, variable are function (if declared with var) or block scoped (if declared with let or const).
  • And you haven't localized the scope of the variable by using var, let or const.

So, it uses the scope in which the function check is defined.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

It is hoisting concept. See the links it will help you understand the concept Scope & Hoisting One more good article. Happy Coding