var, let, and const?let and const be accessed before their declaration due to hoisting? Why or why not?What will be the output of the following code? Explain why.
console.log(x);
var x = 10;
Expected output: undefined
Explanation: Variable x is hoisted but not initialized.
Predict the output and explain:
console.log(a);
let a = 5;
Expected output: ReferenceError: Cannot access 'a' before initialization
Explanation: Variables declared with let are in the Temporal Dead Zone.
Write code to demonstrate how a function declaration is hoisted versus a function expression.
foo();
function foo() {
console.log("I am hoisted!");
}
bar();
const bar = function() {
console.log("I am not hoisted!");
};
Expected output:
I am hoisted!
TypeError: bar is not a function
Fix the following code to avoid hoisting-related issues:
console.log(userName);
var userName = "John";
greet();
function greet() {
console.log("Hello, " + userName);
}
Create an example that explains hoisting of a function inside a block:
if (true) {
test();
function test() {
console.log("Hoisting inside a block!");
}
}
Debug the following code to resolve the hoisting issue and explain the fix:
console.log(num);
var num;
num = 20;
console.log(num);