JavaScript: understanding scope chain [duplicate] - javascript

This question already has answers here:
Javascript function scoping and hoisting
(18 answers)
Closed 3 years ago.
What is the scope chain in following code snippet -
var name = 'John';
function foo() {
if (false) {
var name = 'James';
}
console.log(name);
}
foo();
I got couple of queries regarding this -
Why the logger in function foo is printing undefined even when the variable
is available in global scope? Is it due to the fact that same variable
is re-declared in conditional falsy block and so the global variable is
getting removed from the scope?
Also if we replace the variable declaration under if statement inside function foo from var to let, the logger inside the function foo prints name from global scope. How this is working?

Yes this is because the variables declared with var have function scope and they are hoisted to the top of the function. It logs undefined due to hoisting.
Variables declared with let have block scope so until the if block is not executed the variable name is not declared.
Even if you change it with if(true) it will not work because the variable will only be available inside the block. {} not outside.
Here is the example how let works.
if(true){
let x = 3
}
console.log(x);

If you redeclare variable with var, it has the scope in the whole function. If you do it with let instead of var, it will be available only in the if scope.
var name = 'John';
function foo() {
if (false) {
let name = 'James';
}
console.log(name);
}
foo();

Related

Newbie Questions on Scoping and Hoisting? [duplicate]

This question already has answers here:
What is the temporal dead zone?
(3 answers)
Are variables declared with let or const hoisted?
(7 answers)
Closed 1 year ago.
I am learning Javascript and I got into the hoisting/scoping part. I got some questions that I really hope somebody can help me to clarify and here is my example:
So these works normally due to hoisting - the firstName variable is in Global Scope or function can be called before we declare the function:
function test() {
console.log(firstName);
}
const firstName = 'a';
test();
OR
const firstName ='a';
test();
function test (){
console.log(firstName)
}
However, if I swap the order of firstName and test(), the code does not work anymore:
function test() {
console.log(`${firstName}`)
};
test();
const firstName = 'a';
According to the hoisting, I thought the firstName variable is in the Global Scope. Thereby, the test function should have been able to look up at the variable firstName when it is executed.
But why in the case above, it does not work?
Is there anything wrong with my understanding of hoisting/scoping?
Variables declared with let and const are also hoisted, but unlike for
var the variables are not initialized with a default value of
undefined. Until the line in which they are initialized is executed,
any code that accesses these variables will throw an exception.
MDN DOCS

Difference between local and global variables in javascript? [duplicate]

This question already has answers here:
What is the purpose of the var keyword and when should I use it (or omit it)?
(19 answers)
Closed 6 years ago.
I noticed that in JavaScript, Inside a function some times a variable created without mentioning var before it.
For example :
function myfunction() {
x = 10;
var y = 10;
}
what is the difference between these both?
function myact() {
x = 20;
var y = 10;
console.log(x);
console.log(y);
}
myact();
console.log(x);
//y not available here
var is used for declaration. So, assigning without declaration will simply give it global scope meaning: it will first search if it is available in any scope stack above, if not creates the variable implicitly in global scope and assigns.
JS Docs says:
The scope of a variable declared with var is its current execution
context, which is either the enclosing function or, for variables
declared outside any function, global.
Assigning a value to an undeclared variable implicitly creates it as a
global variable (it becomes a property of the global object) when the
assignment is executed.

Does javascript implement lexical scoping? [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 8 years ago.
Why does this return 2 instead of 1? Seems the second "var" is silently ignored.
function foo()
{
var local = 1;
{
var local = 2;
}
return local;
}
foo()
/*
2
*/
In javascript there is only function level scope and global scope. you cannot create a block scope and it adds no special meaning and does not create any scope.
And this is how your code ends up
function foo()
{
var local = 1;
local = 2;
return local;
}
foo();
In ES6 you can create block level scopes with the help of Let. ES6 is not supported yet. more on that here
From the MDN :
JavaScript does not have block statement scope; rather, a variable
declared within a block is local to the function (or global scope)
that the block resides within.
The scope of a variable in JavaScript is the whole function in which it is declared (or the global scope), so you only have one variable local here.
Your code is equivalent to
function foo()
{
var local;
local = 1;
{
local = 2;
}
return local;
}
foo()
Note that ES6 (the new norm of JavaScript) does introduce a lexical scoping with let but it's not yet really available.

variables scope confusion in javascript [duplicate]

This question already has answers here:
What is the scope of variables in JavaScript?
(27 answers)
Closed 9 years ago.
I was studying the concept of variable scope in JS, found this example on it:
(function() {
var foo = 1;
function bar() {
var foo = 2;
}
bar();
console.log(foo) //outputs 1
if(true) {
var foo = 3;
}
console.log(foo) //outputs 3
})();
output of this function is
1
3
Now I am confused how come foo gets gets value 3 in second log. even when foo is declared by using var in if statement. shouldn't the foo declared in if will have a new instance as it gets in bar()??
if does not introduce a scope block (I understand it does in some langauges). In JavaScript, only function() {} creates a scope block.
There are only two kinds of scope in Javascript; function scope and global scope.
The code inside the if statement doesn't have a scope of its own, so the variable inside the if statement is the same one as the one outside it.
Declaring a variable more than once in a scope doesn't create more than one variable. The var keyword inside the if statement is ignored as the variable already is declared once in the scope, so it's just an assignment.
Note also that the declaration of variables is hoisted to the top of the scope, so even if a declaration is inside a code block that is not executed, the variable is still created:
var foo = 1; // a global variable
(function() {
console.log(foo) //outputs "undefined"
foo = 2; // sets the local variable
if(false) {
var foo = 3; // creates the local variable, but the assignment never happens
}
console.log(foo) //outputs 2
})();
console.log(foo) //outputs 1

JavaScript local and global variable confusion [duplicate]

This question already has answers here:
How do JavaScript closures work?
(86 answers)
Variable: local scope, global scope or is it the JavaScript engine?
(3 answers)
Closed 9 years ago.
I am new to JavaScript and I was doing some practices on local and global variable scopes. Following is my code(fiddle):
var myname = "initial"
function c(){
alert(myname);
var myname = "changed";
alert(myname);
}
c();
When the first alert is called, it is showing myname as undefined. So my confusion is why I am not able to access a global instance of myname and if I don't define myname within the function then it will work fine.
In JavaScript, the variable declarations are automatically moved to the top of the function. So, the interpreter would make it look more like this:
var myname = "initial"
function c(){
var myname;
// Alerts undefined
alert(myname);
myname = "changed";
// Alerts changed
alert(myname);
}
c();
This is called hoisting.
Due to hoisting and the fact that the scope for any variable is the function it's declared in, it's standard practice to list all variables at the top of a function to avoid this confusion.
It is not replacing the global variable. What is happening is called "variable hoisting". That is, var myname; gets inserted at the top of the function. Always initialize your variables before you use them.
Try this:
var myname = "initial";
function c() {
alert(myname);
myname = "changed";
alert(myname);
}
c();

Categories