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 #CodingInterview #WebDevelopment #SoftwareEngineering #Frontend
there is no connection in global variable in this code ,only local or block scope which will be reference error because of 'let' got TDZ accessing before inserting value , but with 'var' there is no issue and printed 20, that's the diference between var and let.
Reference error due to TDZ.
Refernece error scoping is bad! dont need over explaining for that. I think we try to be exact on explaining things that leads to it being more complicated than need be.
It wouldn't print anything, but it would log reference error to console.
ReferenceError... Because inside the block, let a is in the temporal dead zone until it gets initialized.... So console.log(a) runs before let a = 20, that’s why it throws an error...
C. Reference Error The code will try to read the inner a before it's initialized, causing the following error: ReferenceError: Cannot access 'a' before initialization
ReferenceError because the variable 'a' is not a local variable so we need to initialize inside the { }
Reference error. Of course, 90% of people wouldn't write this way. The remaining 10% are people who play roulette with code like this in production
Reference error, because you already have defined variable 'a'. Just remove 'let' from line 4 to remove error
When you enter a block (the code inside { ... }), the JavaScript engine "hoists" the declaration of let a = 20 at the top of that specific block. However, unlike var, variables declared with let are not initialized with a value (not even undefined) until the execution reaches the line where the variable is defined. The period between entering the scope and reaching the line let a = 20 is called the Temporal Dead Zone. Any attempt to access the variable during this time—including a console.log—will crash the script. By declaring let a inside the curly braces, you create a shadowed variable. This tells the engine: "In this specific block, ignore the 'a' from the outside; we have a local 'a' now." Because the engine knows a local variable exists, it refuses to "look up" to the outer scope to find a = 10. It focuses entirely on the local a, finds it hasn't been initialized yet, and throws the error.