Scope chain example [duplicate] - javascript

This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 5 years ago.
So,I am trying to grasp the concept of scope chain in javascript and therefore I created the following example to check if I got it right.
Note: I am familiar with the following concepts(Execution Contexts and Lexical Environments).
Example:
function test(){
function test2(){
//This prints 2 as expected
console.log(a);
}
//This should print 1 but instead it prints undefined
console.log(a);
var a = 2;
test2();
}
var a = 1;
test();
if for example I comment the following:
//var a = 2;
Then the output in both cases is 1.

You should take a look into Hoisting Concept in JavaScript.
the JS engine will move all declaration in the top of the block before going into the execution step.
About your exemple :
function test(){
function test2(){
//This prints 2 as expected
console.log(a);
}
//This should print 1 but instead it prints undefined
console.log(a);
var a = 2;
test2();
}
var a = 1;
test();
will be treated like this
var a; // initialized to undefined
function test(){
var a; // initialized to undefined [which is printed]
function test2(){
//This prints 2 as expected
console.log(a);
}
//This will print undefined which is the actual value of a
console.log(a);
a = 2;
test2();
}
a = 1;
test();
that's why it print undefined

Related

How function declaration is affecting hoisting? [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 1 year ago.
There below two codes print different outputs, despite the inner function not being called.
var a = 1;
function foo(){
a= 2;
}
foo();
console.log(a); // 2
But if I add a function with the same name, the output is different. Although I am not calling the a()
var a = 1;
function foo(){
a= 2;
function a(){
a = 3;
}
}
foo();
console.log(a); // 1
Should not it be 2? Why it logs 1?
Because an identifier named a is declared directly inside the foo function, assignments to variables named a inside the foo function will reference that (local) identifier, and not any possible outer variables named a. It's like:
var a = 1;
function foo(){
// there an identifier named `a` initialized in this scope
var a;
// function declarations are hoisted
a = function a(){
a = 3;
}
// assignment to local identifier `a`
a= 2;
}
foo();
console.log(a); // 1

why is global variable not accessible even if local variable is defined later in code [duplicate]

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 8 years ago.
why does the following code segment generate the following output?
code segment:
var a = 10;
function(){
console.log(a);
var a = 5;
}
output:
undefined
Because variable is hoisted at top and in your function you have declared the variable var a = 5 which is same as following:
var a = 10;
function(){
var a; // a = undefined
console.log(a);//a is not defined so outputs undefined
a = 5;
console.log(a);//a is now 5 so outputs 5
}
And in your function scope var is being declared it doesn't see global variable but local variable i.e. var a and which is undefined.

Variable scope puzzle, prints undefined for variable declared inside function [duplicate]

This question already has answers here:
Surprised that global variable has undefined value in JavaScript
(6 answers)
Closed 8 years ago.
var a = 2;
var b = function(){
console.log(a);
var a = 1;
};
b();
When I call b, it prints undefined. What is the reason?
Inside a function, var declares a function-scoped variable. That means it's visible to the function. The entire function. That means you are print out the variable before assigning a value to it.
var a = 123;
(function () {
a = 456; // Changes the function's "a"
console.log(a); // Outputs the function's "a": 456
var a; // At compile-time, declares a function variable named "a".
})();
console.log(a); // Outputs the global "a": 123
Along the same line, repeating the declaration doesn't do anything. The following prints out 123.
(function () {
var a = 123;
var a;
console.log(a); // 123
})();
The var a in your code is a variable declaration that declares a variable within the scope of its containing function. Due to variable hoisting, variable declarations (like var a) are hoisted to the top of their containing function. While any declaration is hoisted, assignments to that variable are not hoisted, Thus, your code is equivalent to:
var a = 2;
var b = function(){
var a; // hoisted declaration; declares `a` within this function scope
console.log(a);
a = 1; // not-hoisted assignment
};
b();
Since a declared variable is undefined until it is given a value, this code logs undefined.
You have this:
var a = 2;
var b = function(){
console.log(a);
var a = 1;
};
During the run time it becomes:
var a = 2, b;
b = function(){
var a; // new variable declaration with no value assigned
console.log(a); // You used it new "a" without assigning any value
a = 1;
};
Inside the function the a is a new variable because of var keyword and JS is taking this new a in account which is undefined not the global a. Tow variables with same name, one is outside the function (in global scope) and another is inside the function. Since there is a new variable available inside the function so it's being used in console.log(a) but no value assigned.
You may read JavaScript Scoping and Hoisting and var on MDN.

Strange Behavior on Global and Local Variable in JavaScript

I tried following code:
var a = 5;
function x() {
console.log(a);
}
x();
It runs as expected and prints 5.
But i changed the code so the global variable a will be overwrite as follows:
var a = 5;
function x() {
console.log(a);
var a = 1;
}
x();
It prints undefined. It doesn't make sense for me since the overwrite should be happened right after console.log(a). So what is the problem?
This is happening because your second a variable is being 'hoisted' to the top of the function and it hides the first a. What is actually happening is this:
var a = 5;
function x() {
var a;
console.log(a);
a = 1;
}
x();
Here is an article on hoisting from adequately good for further reading on the subject.
var a = 5;
function x() {
var a = 1;
console.log(a);
}
x();
you need to initalize variable a before console.log();

Puzzled by this JavaScript code snippet

For this snippet, I'm not surprised global variable 'a' evaluates to be 5.
http://jsfiddle.net/MeiJsVa23/gZSxY/ :
var a = 10;
function func(){
a = 5;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // and this prints out 5 as expected. No surprise here.
​
But how come for this code snippet, global variable 'a' evaluates to be 10 and not 5? It's as if the a = 5 never happened.
http://jsfiddle.net/MeiJsVa23/2WZ7w/ :
var a = 10;
function func(){
a = 5;
var a = 23;
}
func(); // expect global variable 'a' to be modified to 5;
alert(a); // but this prints out 10!! why?
​
This is due to variable hoisting: anything defined with the var keyword gets 'hoisted' to the top of the current scope, creating a local variable a. See: http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting
So, there are two things are going here: hoisting and shadowing.
Because the first one, variable declarations are "hoisted" to the top, so your code is equivalent to:
var a = 10;
function func(){
var a;
a = 5;
a = 23;
}
And because the second one, you're "shadowed" the global variable a with a local ones, so the changes are not reflected to the global a.
This is called "variable hoisting". var declarations (and function() declarations) are moved to the top of their scope.
This has to do with hoisting.
In the function, a local variable with the same name is declared. Even though it happens after your modification, it is deemed to have been declared before it - this is called hoisting.
Local variables hoist for declaration but not value. So:
function someFunc() {
alert(localVar); //undefined
var localVar = 5;
}
Functions, if declared with function name() {... syntax, hoist for both declaration and value.
function someFunc() {
alert(someInnerFunc()); //5
function someInnerFunc() { return 5; }
}
var a = 10; //a is 10
function func(){
a = 5; //a is 5
var a = 23; // a is now in local scope (via hoisting) and is 23
}
func();
alert(a); // prints global a = 10
Presumably, the statement var a = 23 creates a local variable for the whole scope. So the global a is shadowed for the entirety of func(), not just for the lines below the statement. So in your second snippet, a = 5 is assigning to the local variable declared below.

Categories

Resources