Discussion: Your Code Deserves a Lift
Execute the code to understand the output and gain insights into scoping and hoisting concepts in JavaScript.
Verifying the output
Now, it’s time to execute the code and observe the output.
Press + to interact
let temp = 25;function displayTemperature() {console.log(`Current temperature: ${temp} °C`);}function forecastTemperature() {console.log(`Expected temperature: ${temp} °C`);var temp = 28;}displayTemperature();forecastTemperature();
Understanding the output
You might have expected the output to be:
Current temperature: 25 °CExpected temperature: 25 °C
But this code will actually output:
Current temperature: 25 °CExpected temperature: undefined °C
Variable hoisting
In JavaScript, all declarations are subject to hoisting. This includes var
, let
, const
, function
, function*
, and class
declarations. Hoisting involves the automatic relocation of these declarations to the scope’s beginning, but their initialization is deferred until the execution flow hits the line where hoisting occurred. This process occurs before the code is executed, and it helps JavaScript handle references to variables and functions.
Consider the ...