Unexpected behaviour of JavaScript with let and var keyword [duplicate] - javascript

This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Are variables declared with let or const hoisted?
(7 answers)
Closed 4 years ago.
When i am using var keyword to declare a variable then JS engine is assign default value to "message" at creation stage
console.log(message); //undefined
var message = "My message";
but with let keyword
console.log(message); //message is not defined
let message = "My message";
why this unexpected result or it is something changed in ES6?

This is because of the creation of Temporal dead zone with let
let bindings are created at the top of the (block) scope containing the declaration, commonly referred to as "hoisting". Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.

Related

What is the scope of my variable when I use let? [duplicate]

This question already has answers here:
Do let statements create properties on the global object?
(5 answers)
A javascript 'let' global variable is not a property of 'window' unlike a global 'var' [duplicate]
(1 answer)
What is the difference between "let" and "var"?
(39 answers)
Closed 2 years ago.
Im new in javascript and in programming.
If I declare a variable with var I see that my variable is declared globally and my variable is inside the window object.
Example:
var element1 = 1;
window.element1; //This returns 1
But when I use let I can't access my variable using the window object.
Example:
let element2 = 1;
window.element2; //This returns undefined
So, where has been my variable element2 been declared?
What is the scope of element2 ?
You are confusing scope and automatic attachment to the default object.
If you use let or var outside of any block, function, or module then the scope will be global.
var will also attach a property of the same name to the default object (which is window in the case of JS running in a browser).

Why does it throws reference error for b? [duplicate]

This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
What is the difference between "let" and "var"?
(39 answers)
Closed 2 years ago.
Recently I attended a interview for Frontend development, The interviewer came up with a problem which made me doubt my confidence on javascript. The question is
function some() {
console.log(a) // undefined
console.log(b) // Reference Error: cannot access b before initialization.
var a = 10;
let b = 15
}
I understood hoisting is happening here, but i am not sure why b throwed reference error. Could anyone please explain ?
Unlike variables declared with var, which will start with the value undefined, let variables are not initialized until their definition is evaluated. Accessing the variable before the initialization results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the initialization is processed.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

let vs var in the global scope [duplicate]

This question already has answers here:
What is the difference between "let" and "var"?
(39 answers)
Closed 5 years ago.
Why this will print the names as expected:
var firstName = 'Charlie',
lastName = "Brown"
function showFullName() {
console.log(this.firstName+' '+this.lastName);
}
window.showFullName();
but, if I replace 'var' for 'let', I will get 'undefined' for both firstName & lastName?
I also see that the variables declared using 'var' get attached to the window Object, but the ones declare using 'let'.
Appreciate the help.
Let allows to declare variables which are limited to a particular scope, can be block or expression. Where as var is used for global or local declaration. We can use var instead of let but the reverse fails.

Logging Global variable inside the function Block immediately before redeclaration going undefined: Should not it take the Global Variable Value? [duplicate]

This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
Closed 5 years ago.
let pages =100;
let pageFunction=()=>{
console.log(pages);
const pages = "20";
//console.log(pages);
}
pageFunction();
Output:
Uncaught ReferenceError: pages is not defined
at pageF (:3:13)
at :1:1
According to Mozilla "The let statement declares a block scope local variable, optionally initializing it to a value." Also "At the top level of programs and functions, let, unlike var, does not create a property on the global object."
See
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let for more information.
This means that in the code you gave you effectively create an implicit global variable pages, as let pages is not really global, but restricted to the scope it is in.

Understanding let vs. var hoisting [duplicate]

This question already has answers here:
Are variables declared with let or const hoisted?
(7 answers)
Closed 6 years ago.
With let vs. var I've learned that the major difference is that let variables are scoped to the nearest block and are not hoisted. Also let variables can be reassigned but cannot be redeclared within the same scope. Why then does this code return a "not defined" error?
let x = 10;
if (true) {
console.log(x);
let x = 11;
}
returns:
Uncaught ReferenceError: x is not defined(…)
While:
let x = 10;
if (true) {
console.log(x);
}
logs 10 without an error?
The main difference between var and let is that:
var is hoisted to the wrapping function block.
let is hoisted to the wrapping {} block
The second code sample doesn't have the same reference conflict as the first because you're declaring x prior to referencing it in the following if block.
EDIT To address Pointy's comment below:
You're experiencing the ReferenceError because of the temporal dead zone
If you reference a variable defined by let within the same block before it is defined you will receive this error.
From MDN let Docs
In ECMAScript 2015, let will hoist the variable to the top of the block. However, referencing the variable in the block before the variable declaration results in a ReferenceError. The variable is in a "temporal dead zone" from the start of the block until the declaration is processed.
function do_something() {
console.log(foo); // ReferenceError
let foo = 2;
}
let variables are actually hoisted (within the block). From MDN:
In ECMAScript 2015, let will hoist the variable to the top of the block.

Categories

Resources