JavaScript Temporal Dead Zone and Scope

90% of developers get this wrong. Let’s see if you’re in the 10%. What does this code print? let a = 10; { console.log(a); let a = 20; } Comment ONLY ONE answer: A) 10 B) 20 C) ReferenceError D) undefined No googling. No running it. Just reasoning. Understanding scope and the Temporal Dead Zone is what separates memorization from mastery. JavaScript Mastery w3schools.com #JavaScript #CodingInterview #WebDevelopment #SoftwareEngineering #Frontend

  • No alternative text description for this image

Appreciate you mentioning us💚

10; lexical scoping; child scopes exist within the parent; it might be different though, if you've used 'var' instead of 'let'

Reference error, At first a is initialised to 10, then block starts { } , and inside that block js sees let a = 20, So before execution js creates a block scoped a for that block, now the inner a is hoisted on top of this block, but it stays uninitialised until the line: let a = 20 The time between the start of block and initialization is called the Temporal Dead Zone (TDZ), so even though outer a = 10 exists, inner a shadows it completely. The local a is still in TDZ, when console.log(a) runs, so : ReferenceError: Cannot access 'a' before initialization.

And this is why javascript developers go insane... That's not a function, it's a code nesting with a virtual rat. If I saw this in code, there would be firing.

This is a scope problem the first is a global one and the next is a block scope. There will be Reference error because when you use the let or const assignment in a block scope it is confined unlike the var that is not.

Reference error due to temporal dead zone.in case of let and var hoisting is not working properly.

Should be 10 - can't be 20 because let doesn't get hoisted, and the child scope can read from the parent scope. But if I saw this in the wild, I'd hit git blame and ask why. 😅

Reference error. Reason is let is not hoisted as var does. So the a variables remain in its TDZ until it initializes in the block. If the same thing happens with var then the answer is 10.

reference error Reason: Let is block scope. It cannot access before initialisation

See more comments

To view or add a comment, sign in

Explore content categories