Share
Explore

s24 Assignment 1 CSD 3103 s1

image.png

Variable Hoisting and the Temporal Dead Zone


Theme: Space Mission to Mars

Welcome, Cadet! As part of our Mars mission training, you'll be diving deep into the concepts of variable hoisting and the temporal dead zone in JavaScript.
Your mission is to complete a series of exercises that simulate real-world programming scenarios you might encounter while coding for our space missions.

Let's prepare you for the challenges ahead!


Table of Contents

1. Introduction to Variable Hoisting 2. Understanding the Temporal Dead Zone 3. Exercise 1: Analyzing Variable Hoisting 4. Exercise 2: Avoiding Temporal Dead Zone Errors 5. Exercise 3: Refactoring Code for Better Hoisting Practices 6. Exercise 4: Debugging Temporal Dead Zone Issues 7. Exercise 5: Implementing Safe Variable Declarations 8. Exercise 6: Building a Hoisting-Safe Mars Rover Control System

1. Introduction to Variable Hoisting

Variable hoisting is a JavaScript mechanism where variable declarations are moved, or "hoisted", to the top of their containing scope during the compile phase.
This means you can use variables before they are declared.

However, only the declarations are hoisted, not the initializations.

console.log(planet); // undefined var planet = 'Mars'; In the example above, the declaration `var planet` is hoisted, but the initialization `planet = 'Mars'` is not.

2. Understanding the Temporal Dead Zone
The Temporal Dead Zone (TDZ) is a behavior related to `let` and `const` variables.
It refers to the time span between the entering of the scope and the actual declaration of the variable, during which accessing the variable will result in a ReferenceError.
console.log(rocket); // ReferenceError let rocket = 'Falcon 9';
In this case, accessing `rocket` before its declaration will throw an error due to the TDZ.

3. Exercise 1: Analyzing Variable Hoisting
**Objective:** Identify the behavior of variable hoisting in the provided code snippets.
**Instructions:** - Review each code snippet. - Predict the output. - Run the code to check your predictions.
**Code Snippets:**
1. ```javascript console.log(crewMember); // ? var crewMember = 'Alice'; console.log(crewMember); // ? ```
2. ```javascript var mission = 'Mars Exploration'; console.log(mission); // ? var mission = 'Lunar Landing'; console.log(mission); // ? ```
**Questions:** 1. What is the output of each `console.log` statement? 2. How does hoisting affect the variable declarations?
---

4. Exercise 2: Avoiding Temporal Dead Zone Errors

**Objective:** Understand and avoid the Temporal Dead Zone errors.

**Instructions:** - Examine each code snippet. - Predict if the code will throw an error. - Run the code to confirm your prediction.
**Code Snippets:**
1. ```javascript console.log(spacecraft); // ? let spacecraft = 'Orion'; console.log(spacecraft); // ? ```
2. ```javascript const destination = 'Mars'; console.log(destination); // ? { console.log(destination); // ? let destination = 'Moon'; console.log(destination); // ? }
**Questions:** 1. Which `console.log` statements will throw errors and why? 2. How can you refactor the code to avoid TDZ errors?

5. Exercise 3: Refactoring Code for Better Hoisting Practices
**Objective:** Refactor code to improve readability and avoid potential hoisting pitfalls.
**Instructions:** - Refactor the given code snippets to use best practices for variable declarations. - Ensure the code runs without errors.
**Code Snippets:**
1. function launchRocket() { console.log(rocketType); var rocketType = 'Falcon Heavy'; console.log(rocketType); } launchRocket(); ```
2. ```javascript var launchTime = '10:00 AM'; function scheduleLaunch() { console.log(launchTime); var launchTime = '2:00 PM'; console.log(launchTime); } scheduleLaunch(); ```
**Task:** Refactor the code so that variable declarations are clear and predictable.
---
6. Exercise 4: Debugging Temporal Dead Zone Issues
**Objective:** Identify and fix TDZ issues in the provided code snippets.
**Instructions:** - Analyze the code snippets for TDZ issues. - Correct the code to prevent errors.
**Code Snippets:**
1. ```javascript console.log(astronaut); // ? let astronaut = 'Neil Armstrong'; ```
2. ```javascript { console.log(oxygenLevel); // ? const oxygenLevel = 'Safe'; console.log(oxygenLevel); // ? } ```
**Task:** Identify the lines causing TDZ errors and modify the code to eliminate these errors.
---
7. Exercise 5: Implementing Safe Variable Declarations

Objective: Implement best practices for variable declarations to avoid hoisting and TDZ issues.

**Instructions:** - Rewrite the given code snippets using `let` and `const`. - Ensure the code is clean and error-free.
**Code Snippets:**
1. ```javascript var base = 'Alpha'; console.log(base); var base = 'Bravo'; console.log(base); ```
2. ```javascript function prepareRations() { var rations = 'Ready'; console.log(rations); var rations = 'Packed'; console.log(rations); } prepareRations();
**Task:**

Use `let` and `const` to declare variables and refactor the code for better readability and error prevention.

---
### 8. Exercise 6: Building a Hoisting-Safe Mars Rover Control System
**Objective:** Create a simple Mars rover control system that adheres to best practices for variable hoisting and TDZ.

Instructions:

- Design a control system with commands to move the rover. - Ensure all variable declarations use `let` or `const`. - Test the system to confirm it works correctly without hoisting or TDZ issues.
**Sample Code Structure:** function MarsRoverControl() { let position = { x: 0, y: 0 }; const commands = ['MOVE_FORWARD', 'TURN_LEFT', 'TURN_RIGHT'];
function executeCommand(command) { switch (command) { case 'MOVE_FORWARD': position.y += 1; break; case 'TURN_LEFT': position.x -= 1; break; case 'TURN_RIGHT': position.x += 1; break; default: console.log('Invalid command'); } }
function getPosition() { return position; }
return { executeCommand, getPosition }; }
const rover = MarsRoverControl(); rover.executeCommand('MOVE_FORWARD'); console.log(rover.getPosition()); // { x: 0, y: 1 } rover.executeCommand('TURN_LEFT'); console.log(rover.getPosition()); // { x: -1, y: 1 } ```
**Task:** Complete the control system implementation, ensuring all commands work correctly and variables are safely declared.
---
Congratulations, Cadet! Completing these exercises has prepared you to handle variable hoisting and the temporal dead zone in JavaScript.
These skills will be crucial as you continue your journey in coding and space exploration. Keep practicing and exploring!
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.