Use strict and let not working as expected in Javascript - javascript

I declared variables twice in my function while I am using "use strict". I know this function has global scope and it's variables are also treated as global with window scope i.e window.car
But It should not re-declare speed and capacity variables inside if statement with let data type. ( "let" Declares a block scope local variable, optionally initializing it to a value. )
(function car() {
"use strict";
var speed = 100;
const capacity = '1000CC';
if(speed) {
let speed = 200;
let capacity = '5000CC';
console.log(speed,capacity);
}
console.log(speed,capacity);
})();
Please let me know what I am missing here.

"let" Declares a block scope local variable. But still global variable can be modified in local scope.
(function car() {
"use strict";
var speed = 100;
const capacity = '1000CC';
if(speed) {
let speed = 200;
let capacity = '5000CC';
console.log(speed,capacity);//inside local it is modified to 200
}
console.log(speed,capacity);//outside scope it pull from global scope to 100
})();
You can re-declare / modify the global variables even in strict mode.
You'll only get error when you re-declare the same variable in same scope. Look at the following example taken from MDN
if (x) {
let foo;
let foo; // TypeError thrown.
}
However, function bodies do not have this limitation! (But it throws an error in ES6 though as commented by #Bergi, may be there's wrong documentation in MDN)
function do_something() {
let foo;
let foo; // This works fine.
}

The variable speed declared with var and the speed declared with let are two different variables.
Inside the body of the if statement, the local declaration of speed hides the variable declared in the outer block - it doesn't redeclare it.

Related

What is execution context of of globally declared let ,const and Arrow Function In JavaScript [duplicate]

I have been playing with ES6 for a while and I noticed that while variables declared with var are hoisted as expected...
console.log(typeof name); // undefined
var name = "John";
...variables declared with let or const seem to have some problems with hoisting:
console.log(typeof name); // ReferenceError
let name = "John";
and
console.log(typeof name); // ReferenceError
const name = "John";
Does this mean that variables declared with let or const are not hoisted? What is really going on here? Is there any difference between let and const in this matter?
#thefourtheye is correct in saying that these variables cannot be accessed before they are declared. However, it's a bit more complicated than that.
Are variables declared with let or const not hoisted? What is really going on here?
All declarations (var, let, const, function, function*, class) are "hoisted" in JavaScript. This means that if a name is declared in a scope, in that scope the identifier will always reference that particular variable:
x = "global";
// function scope:
(function() {
x; // not "global"
var/let/… x;
}());
// block scope (not for `var`s):
{
x; // not "global"
let/const/… x;
}
This is true both for function and block scopes1.
The difference between var/function/function* declarations and let/const/class declara­tions is the initialisation.
The former are initialised with undefined or the (generator) function right when the binding is created at the top of the scope. The lexically declared variables however stay uninitialised. This means that a ReferenceError exception is thrown when you try to access it. It will only get initialised when the let/const/class statement is evaluated, everything before (above) that is called the temporal dead zone.
x = y = "global";
(function() {
x; // undefined
y; // Reference error: y is not defined
var x = "local";
let y = "local";
}());
Notice that a let y; statement initialises the variable with undefined like let y = undefined; would have.
The temporal dead zone is not a syntactic location, but rather the time between the variable (scope) creation and the initialisation. It's not an error to reference the variable in code above the declaration as long as that code is not executed (e.g. a function body or simply dead code), and it will throw an exception if you access the variable before the initialisation even if the accessing code is below the declaration (e.g. in a hoisted function declaration that is called too early).
Is there any difference between let and const in this matter?
No, they work the same as far as hoisting is regarded. The only difference between them is that a constant must be and can only be assigned in the initialiser part of the declaration (const one = 1;, both const one; and later reassignments like one = 2 are invalid).
1: var declarations are still working only on the function level, of course
Quoting ECMAScript 6 (ECMAScript 2015) specification's, let and const declarations section,
The variables are created when their containing Lexical Environment is instantiated but may not be accessed in any way until the variable’s LexicalBinding is evaluated.
So, to answer your question, yes, let and const hoist but you cannot access them before the actual declaration is evaluated at runtime.
ES6 introduces Let variables which comes up with block level scoping. Until ES5 we did not have block level scoping, so the variables which are declared inside a block are always hoisted to function level scoping.
Basically Scope refers to where in your program your variables are visible, which determines where you are allowed to use variables you have declared. In ES5 we have global scope,function scope and try/catch scope, with ES6 we also get the block level scoping by using Let.
When you define a variable with var keyword, it's known the entire function from the moment it's defined.
When you define a variable with let statement it's only known in the block it's defined.
function doSomething(arr){
//i is known here but undefined
//j is not known here
console.log(i);
console.log(j);
for(var i=0; i<arr.length; i++){
//i is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
for(let j=0; j<arr.length; j++){
//j is known here
}
//i is known here
//j is not known here
console.log(i);
console.log(j);
}
doSomething(["Thalaivar", "Vinoth", "Kabali", "Dinesh"]);
If you run the code, you could see the variable j is only known in the loop and not before and after. Yet, our variable i is known in the entire function from the moment it is defined onward.
There is another great advantage using let as it creates a new lexical environment and also binds fresh value rather than keeping an old reference.
for(var i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
for(let i=1; i<6; i++){
setTimeout(function(){
console.log(i);
},1000)
}
The first for loop always print the last value, with let it creates a new scope and bind fresh values printing us 1, 2, 3, 4, 5.
Coming to constants, it work basically like let, the only difference is their value can't be changed. In constants mutation is allowed but reassignment is not allowed.
const foo = {};
foo.bar = 42;
console.log(foo.bar); //works
const name = []
name.push("Vinoth");
console.log(name); //works
const age = 100;
age = 20; //Throws Uncaught TypeError: Assignment to constant variable.
console.log(age);
If a constant refers to an object, it will always refer to the object but the object itself can be changed (if it is mutable). If you like to have an immutable object, you could use Object.freeze([])
As per ECMAScript® 2021
Let and Const Declarations
let and const declarations define variables that are scoped to the running execution context's LexicalEnvironment.
The variables are created when their containing Environment Record is instantiated but may not be accessed in any way until the variable's LexicalBinding is evaluated.
A variable defined by a LexicalBinding with an Initializer is assigned the value of its Initializer's AssignmentExpression when the LexicalBinding is evaluated, not when the variable is created.
If a LexicalBinding in a let declaration does not have an Initializer the variable is assigned the value undefined when the LexicalBinding is evaluated.
Block Declaration Instantiation
When a Block or CaseBlock is evaluated a new declarative Environment Record is created and bindings for each block scoped variable, constant, function, or class declared in the block are instantiated in the Environment Record.
No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.
Top Level Lexically Declared Names
At the top level of a function, or script, function declarations are treated like var declarations rather than like lexical declarations.
Conclusion
let and const are hoisted but not initialized.
Referencing the variable in the block before the variable declaration results in a ReferenceError, because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
Examples below make it clear as to how "let" variables behave in a lexical scope/nested-lexical scope.
Example 1
var a;
console.log(a); //undefined
console.log(b); //undefined
var b;
let x;
console.log(x); //undefined
console.log(y); // Uncaught ReferenceError: y is not defined
let y;
The variable 'y' gives a referenceError, that doesn't mean it's not hoisted. The variable is created when the containing environment is instantiated. But it may not be accessed bcz of it being in an inaccessible "temporal dead zone".
Example 2
let mylet = 'my value';
(function() {
//let mylet;
console.log(mylet); // "my value"
mylet = 'local value';
})();
Example 3
let mylet = 'my value';
(function() {
let mylet;
console.log(mylet); // undefined
mylet = 'local value';
})();
In Example 3, the freshly declared "mylet" variable inside the function does not have an Initializer before the log statement, hence the value "undefined".
Source
ECMA
MDN
From MDN web docs:
In ECMAScript 2015, let and const are hoisted but not initialized. Referencing the variable in the block before the variable declaration results in a ReferenceError because the variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
console.log(x); // ReferenceError
let x = 3;
in es6 when we use let or const we have to declare the variable before using them.
eg. 1 -
// this will work
u = 10;
var u;
// this will give an error
k = 10;
let k; // ReferenceError: Cannot access 'k' before initialization.
eg. 2-
// this code works as variable j is declared before it is used.
function doSmth() {
j = 9;
}
let j;
doSmth();
console.log(j); // 9
let and const are also hoisted.
But an exception will be thrown if a variable declared with let or const is read before it is initialised due to below reasons.
Unlike var, they are not initialised with a default value while hoisting.
They cannot be read/written until they have been fully initialised.

In the block scope even after initialisation with undefined var type of variable logs out unexpected value

function show() {
var x = 10;
if (true) {
var x = 20;
}
console.log(x); // 20
}
show();
But when I not initialise the 'x' manually which is inside the 'if-statement', it initialise with undefined and hoisted to the top and should log the most recent value which is undefined , as 20 is logs out in the above example. But it logs out 10.Why?
function show() {
var x = 10;
if (true) {
var x;
}
console.log(x); // 10
}
show();
From MDN - var:
Duplicate variable declarations using var will not trigger an error,
even in strict mode, and the variable will not lose its value, unless
another assignment is performed.
So, unless you re-assign any value to x, variable declared with var will keep its value.
Re-declaring x inside the if block does not create a new variable; x is created only once.
From the Ecmascript spec - 14.3.2 Variable Statement:
A var statement declares variables that are scoped to the running
execution context's VariableEnvironment. Var variables are created
when their containing Environment Record is instantiated and are
initialized to undefined when created. Within the scope of any
VariableEnvironment a common BindingIdentifier may appear in more than
one VariableDeclaration but those declarations collectively define
only one variable.
That is why x in the following statement
var x;
doesn't implicitly gets initialized with undefined; this re-declaration statement didn't re-create the variable x.
function show() {
var x = 10;
if (true) {
var x = undefined; // re-assigned
}
console.log(x);
}
show();
Note on hoisting: Unless you know this already, variables are NOT literally hoisted/moved to the top of the scope in which they are declared; variable declarations are processed before the code execution, this is why they appear to have moved to the top of the scope.
For more details, see: MDN - var hoisting
So if you are trying to relate above both example, you might confused. see both examples in different way, you will get the answer.

Always declare local variables

W3School saying that All variables used in a function should be declared as local variables.
Local variables must be declared with the var keyword, otherwise they will become global variables.
function multiply () {
var x = 10;
var y = 20;
return x * y;
};
function multiply () {
let x = 10;
let y = 20;
return x * y;
};
But let variables in 2nd function are still local variables.
How local variables declared with other than var keyword could become global variables?
How local variables declared with other than var keyword could become global variables?
They cannot. Every variable declared with var, let or const will be scoped to the current (function / block) scope. W3Schools is just a bit outdated.
Let and const came into picture after es6. They are mainly used to add block scope to a variable. Using the Javascript MDN will give you a clear picture about how exactly both these keywords work.
"Local variables must be declared with the var keyword, otherwise they will become global variables". This statement is no longer correct, your source of information might be outdated.
https://hackernoon.com/js-var-let-or-const-67e51dbb716f - this article might help.

what is block scope function ECMAScript 6 compare with ECMAScript 5 [duplicate]

This question already has answers here:
What are the precise semantics of block-level functions in ES6?
(2 answers)
Closed 7 years ago.
What is block scope function in ECMAScript 6?
Can anyone help me understand the main difference in the block scope function compared to ECMAScript 5?
The new let and const in ES2015 (aka "ES6") have four major differences compared with the venerable var:
They have block scope
They aren't hoisted (well, they're sort of hoisted, but in a useful way)
Repeated declarations are errors
When used at global scope, they don't create properties of the global object (despite creating global variables; this is a new concept as of ES2015)
(For what it's worth, this is covered in detail in Chapter 2 of my recent book JavaScript: The New Toys, which covers ES2015-ES2020.)
Block scope
var variables exist throughout the function they're declared in (or globally, if declared globally), they aren't confined to the block they're in. So this code is valid:
function foo(flag) {
a = 10;
if (flag) {
var a = 20;
}
return a;
}
console.log(foo(false)); // 10
console.log(foo(true)); // 20
a is defined regardless of whether flag is true and it exists outside the if block; all three as above are the same variable.
That's not true of let (or const):
function foo(flag) {
if (flag) {
let a = 10;
}
return a; // ReferenceError: a is not defined
}
console.log(foo(true));
a only exists inside the block it's declared in. (For for statements, a declaration within the () of the for is handled very specially: a new variable is declared within the block for each loop iteration.) So outside the if, a doesn't exist.
let and const declarations can shadow declarations in an enclosing scope, e.g.:
function foo() {
let a = "outer";
for (let a = 0; a < 3; ++a) {
console.log(a);
}
console.log(a);
}
foo();
That outputs
0
1
2
outer
...because the a outside the for loop isn't the same a as the one inside the for loop.
Hoisting
This is valid code:
function foo() {
a = 5;
var a = a * 2;
return a;
}
Bizarre-looking, but valid (it returns 10), because var is done before anything else is done in the function, so that's really:
function foo() {
var a; // <== Hoisted
a = 5;
a = a * 2; // <== Left where it is
return a;
}
That's not true of let or const:
function foo() {
a = 5; // <== ReferenceError: a is not defined
let a = a * 2;
return a;
}
You can't use the variable until its declaration. The declaration isn't "hoisted" (well, it's partially hoisted, keep reading).
Earlier I said
They aren't hoisted (well, they're sort of hoisted, but in a useful way)
"Sort of"? Yes. A let or const declaration shadows an identifier throughout the block in which it appears, even though it only actually takes effect where it occurs. Examples help:
function foo() {
let a = "outer";
for (let x = 0; x < 3; ++x) {
console.log(a); // ReferenceError: a is not defined
let a = 27;
}
}
Note that instead of getting "outer" in the console, we get an error. Why? Because the let a in the for block shadows the a outside the block even though we haven't gotten to it yet. The space between the beginning of the block and the let is called the "temporal dead zone" by the spec. Words aren't everybody's thing, so here's a diagram:
Repeated declarations
This is valid code:
function foo() {
var a;
// ...many lines later...
var a;
}
The second var is simply ignored.
That's not true of let (or const):
function foo() {
let a;
// ...many lines later...
let a; // <== SyntaxError: Identifier 'a' has already been declared
}
Globals that aren't properties of the global object
JavaScript has the concept of a "global object" which holds various global things as properties. In loose mode, this at global scope refers to the global object, and on browsers there's a global that refers to the global object: window. (Some other environments provide a different global, such as global on NodeJS.)
Until ES2015, all global variables in JavaScript were properties of the global object. As of ES2015, that's still true of ones declared with var, but not ones declared with let or const. So this code using var at global scope, on a browser, displays 42:
"use strict";
var a = 42; // Global variable called "a"
console.log(window.a); // Shows 42, because a is a property of the global object
But this code shows undefined for the properties, because let and const at global scope don't create properties on the global object:
"use strict";
let a = 42; // Global variable called "a"
console.log(a); // 42 (of course)
console.log(window.a); // undefined, there is no "a" property on the global object
const q = "Life, the Universe, and Everything"; // Global constant
console.log(q); // "Life, the Universe, and Everything" (of course)
console.log(window.q); // undefined, there is no "q" property on the global object
Final note: Much of the above also holds true if you compare the new ES2015 class (which provides a new, cleaner syntax for creating constructor functions and the prototype objects associated with them) with function declarations (as opposed to function expressions):
class declarations have block scope. In contrast, using a function declaration within a flow-control block is invalid. (It should be a syntax error; instead, different JavaScript engines handle it differently. Some relocate it outside the flow-control block, others act as though you'd used a function expression instead.)
class declarations aren't hoisted; function declarations are.
Using the same name with two class declarations in the same scope is a syntax error; with a function declaration, the second one wins, overwriting the first.
class declarations at global scope don't create properties of the global object; function declarations do.
Just as a reminder, this is a function declaration:
function Foo() {
}
These are both function expressions (anonymous ones):
var Foo = function() {
};
doSomething(function() { /* ... */ });
These are both function expressions (named ones):
var Foo = function Foo() {
};
doSomething(function Foo() { /* ... */ });

Javascript Global vs Local Scope

I'm currently trying to understand Javascript's interesting take on global vs local scope.
My question is that why would the following returns undefined?
var a = 100;
function local() {
if (false) {
var a = 50;
}
alert(a);
}
Additionally, I ran this:
var a = 100;
function local() {
alert(a);
}
The result was a resounding: 100.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
Because of hoisting.
It means every variable declaration get's popped to the top of the function so the actual code that runs is:
var a = 100;
function local(){
var a;
if (false)
a = 50;
alert(a);
}
It has very little to do with global VS. local, you simply hid the outer a variable with the inner a variable.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
No
Regarding the question in the comment "In the case that I want to revert to using a global variable in case the if condition fails (which I intentionally did), how can I do so? ":
You can use eval:
var a = 100;
function local() {
if (false) {
eval('var a = 50;');
}
alert(a);
}
Live DEMO
But you should not!
JavaScript has function scope, not block scope (as many other programming languages). That means regardless where the var statement occurs (in your case, an if-branch that is not even executed), it declares a variable a in the function's local scope. It shadows the global a variable, but since it has no value assigned it returns undefined.
Is there some way that we can specify when we want the variable to be taken from the global scope, like a PHP global keyword, that we can use with Javascript?
You can access the variable as a property of the global object (window in browser environments):
var a = 100; // global
function loc() {
var a = 50;
alert(window.a); // 100
alert(a); // 50
}
loc();
However, you will hardly use this. Global variables are to be avoided in general, and in case of name clashes you should simply rename your local variable (for readability and maintainability at least).
I know that if a variable is in defined inside a function using var, then it will have Local Scope.
I also know that any function has easy access to Global variable.
When I tested following in Console of Browser, first output was undefined.
It means that function nwf() was unable to access Global variable nw1
This is due to reference error which highlights importance of Strict Mode
To avoid such scenario, never re-declare and/or initialize any variable with same name inside and outside any function, just unlike following:-
var nw1 = 1; // var creates global scope outside function
function nwf() {
alert(nw1);
var nw1 = 2; // var creates LOCAL scope inside function
alert(nw1);
};
nwf();

Categories

Resources