0
0
Javascriptprogramming~5 mins

Common hoisting pitfalls in Javascript - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is hoisting in JavaScript?
Hoisting is JavaScript's behavior of moving variable and function declarations to the top of their containing scope before code execution.
Click to reveal answer
beginner
Why can using var cause unexpected behavior due to hoisting?
Variables declared with var are hoisted and initialized with undefined, so accessing them before assignment returns undefined instead of an error.
Click to reveal answer
intermediate
What happens when you try to access a let or const variable before its declaration?
Accessing let or const variables before declaration causes a ReferenceError due to the temporal dead zone (TDZ).
Click to reveal answer
intermediate
How does function declaration hoisting differ from function expression hoisting?
Function declarations are fully hoisted, so you can call them before they appear in code. Function expressions assigned to variables are hoisted only as variable declarations, so calling them before assignment causes errors.
Click to reveal answer
advanced
What is a common pitfall when using var inside loops related to hoisting?
Using var inside loops hoists the variable to the function scope, causing all iterations to share the same variable, which can lead to unexpected results in closures.
Click to reveal answer
What will be the output of this code?<br>
console.log(x); var x = 5;
AReferenceError
B5
Cnull
Dundefined
What happens if you try to access a let variable before its declaration?
AOutputs undefined
BOutputs null
CThrows ReferenceError
DOutputs 0
Which of these is fully hoisted and can be called before its declaration?
AFunction declaration
BFunction expression assigned to var
CArrow function assigned to const
DClass declaration
What is the output of this code?<br>
for(var i=0; i<3; i++) { setTimeout(() => console.log(i), 100); }
A0 1 2
B3 3 3
Cundefined undefined undefined
DReferenceError
Which keyword avoids hoisting pitfalls by block-scoping variables?
ABoth B and D
Blet
Cfunction
Dconst
Evar
Explain what hoisting is and describe a common pitfall when using var in JavaScript.
Think about how JavaScript moves declarations and what happens if you use a variable before assigning it.
You got /4 concepts.
    Describe the difference between function declarations and function expressions in terms of hoisting.
    Consider which functions you can call before they appear in the code.
    You got /4 concepts.