Understanding let vs. var hoisting [duplicate]

2024/2/27 8:21:02

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?

Answer

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); // ReferenceErrorlet foo = 2;}

http://en.ppmy.cn/q/42747.html

Related Q&A

ReactJS onClick state change one step behind

Im building a very primitive quiz app with ReactJS and Im having trouble updating the state of my Questions component. Its behavior is it renders the correct index of the questions array to the DOM de…

Event delegation on mouseover

When creating click events, I do my best to bind them only once – generally to a parent shared by all the nodes expected to trigger the event. Im curious, however, what the best practice is with mouse…

Replicating Java password hashing code in Node.js (PBKDF2WithHmacSHA1)

Edit: my question has been updated, check the bottom of this post for the latest issue. I left the rest up for people who want to read the whole story :)Ive been working on translating a small Java app…

How do you get an ID of a clicked div element in JavaScript?

My question is how to get an ID of an element that has just been clicked? (JavaScript)

Is `Object.freeze(Object.prototype)` only the hazard for extending `Object.prototype` with Symbols?

So, fundamentally, this question is Not opinion-based. I seriously pursuit this issue objectively without feeling mostly arisen from the predominant opinion - Why is extending native objects a bad prac…

Drag cursor in javascript?

I need to set the drag cursor in some places, but I cant see it listed here http://www.w3schools.com/cssref/pr_class_cursor.asp In my case it appears when I drag some image :http://s2.subirimagenes.com…

Error: EPERM: operation not permitted, scandir

please I am running a react native project but when I run the npx react-native run-android command, I get the error below error EPERM: operation not permitted, scandir C:/Users/REO/AppData/Local/Applic…

correct way to handle errors inside a Promise

Currently, Im trying to decide what pattern I should use while dealing with errors inside a Promise. For instance, I have the code belowpromiseFunc() .then(result => {console.info(`.THEN:: ${result}…

Disable media control keys with javascript

Im building a keyboard-like application on a website using javascript (no jQuery), but instead of one note being played a sound file plays/pauses every time you click on an image. Ive managed to get it…

Remove fullscreen window decoration/border Chrome OS app/kiosk mode

I have a web application that I want to run in kiosk mode on a chromebox. So far Ive pretty much got it all working, but I cant seem to get rid of the annoying big white border around the screen. A scr…