Sprint 6 Flashcards
Objects and Event Handling in JavaScript
What is the Temporal Dead Zone “TDZ” in JS
TT DOT/VScode explanation
Ah, great question! Let me explain the Temporal Dead Zone (TDZ) in a fun and practical way.
Think of the TDZ like trying to use a phone before you’ve unboxed it. Even though you bought the phone (declared the variable), until you actually unbox it and set it up (initialize it), you can’t use it! That’s exactly what the TDZ is in JavaScript.
Here’s a simple example:
JavaScript
// TDZ starts here for myVariable
console.log(myVariable); // 💥 Error! We’re in the TDZ
let myVariable = “Hello”; // TDZ ends here
Key points about TDZ:
1. It mainly affects let and const declarations (not var)
2. It exists from the start of the block until the declaration is processed
3. It helps catch potential bugs by preventing access to variables before they’re properly set up
Here’s another real-world example:
```javascript
// This will fail
const greeting = “Hello “ + name; // In TDZ for ‘name’
const name = “Sarah”;
// This works
const name = “Sarah”;
const greeting = “Hello “ + name; // ‘name’ is initialized
~~~
How does “var”, “let”, and “const” behave with TDZ in JavaScript?
TT DOT/VScode explanation
Awesome enthusiasm! Let’s compare how var, let, and const behave with TDZ through some practical examples:
// With var
console.log(varVariable); // Output: undefined (Not an error! This is “hoisting”)
var varVariable = “Hello”;
// With let
console.log(letVariable); // 💥 ReferenceError: Cannot access before initialization
let letVariable = “Hello”;
// With const
console.log(constVariable); // 💥 ReferenceError: Cannot access before initialization
const constVariable = “Hello”;
Key differences:
1. var:
- Gets “hoisted” to the top of its scope
- Initialized with undefined before your code runs
- No TDZ! (but this can lead to bugs)
let and const:
Declarations are hoisted but NOT initialized
Strictly enforces TDZ
Gives you helpful errors instead of undefined
Here’s a tricky example that developers often encounter:
```javascript
var myName = “Outer”;
function example() {
console.log(myName); // With var: undefined
// With let/const: 💥 ReferenceError
let/var myName = “Inner”;
}
~~~
Extras from Dot
You’re welcome! That’s a great observation about let/const being safer - they help catch potential issues early by making it clear when we’re trying to use variables before they’re ready.
And I love your approach of planning to practice later! That’s a smart way to learn - understand the concept first, then reinforce it with hands-on practice when you have time.
Good luck with your coding, and feel free to come back if you have any more questions! Keep up that enthusiasm for learning! 👍