Does javascript implement lexical scoping? [duplicate] - javascript

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.

Related

JavaScript: understanding scope chain [duplicate]

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();

why let keyword does not work with eval() [duplicate]

This question already has answers here:
Define const variable using eval()
(2 answers)
Closed 4 years ago.
function foo(str, a) {
eval( str );
console.log( a, b );
}
foo( "var b = 3;", 1 );
This works just fine, but when we use let instead of var, it does not work. Why?
Because eval introduces a new block of code. The declaration using var will declare a variable outside of this block of code, since var declares a variable in the function scope.
let, on the other hand, declares a variable in a block scope. So, your b variable will only be visible in your eval block. It's not visible in your function's scope.
More on the differences between var and let
EDIT : To be more precise eval + let do, in fact, create a Lexical Environment. See #RobG response in Define const variable using eval()

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.

Javascript variable declaration, why is this legal? [duplicate]

This question already has answers here:
What is the (function() { } )() construct in JavaScript?
(28 answers)
Closed 8 years ago.
I just encountered this variable declaration syntax for the first time.
var myVar = (function() {
return 1;
})();
My 2 main questions are..
What is it called, and why is it legal?
Forgive me if this question has been asked before, I tried searching around but I have no idea what this notation is called so I wasn't able to find anything.
Also, I should add, what is the function of the 2 sets of parentheses? The first of which encloses the function, the second of which is empty.
Self executing functions are typically used to encapsulate context and avoid name collusions. Any variable that you define inside the (function(){..})() are not global.
The following code:
var same_name = 1;
var myVar = (function() {
var same_name = 2;
console.log(same_name);
})();
console.log(same_name);
produces this output:
1
2
By using this syntax you avoid colliding with global variables declared elsewhere in you javascript code.
I am not sure what this is called, other than defining an anonymous function and immediately invoking it.
It is perfectly legal, because
Defining an anonymous function is legal.
Invoking it and assigning the return value is also legal.
The end result is that myVar = 1.
This is an anonymous function (also called lambda function) that is being executed immediately with its return value (1) being assigned to a variable (myVar). It's legal because the specification says it is. It is a very common feature in many languages.

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

Categories