Challenge - 5 Problems
Var Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of var variable hoisting
What is the output of this JavaScript code?
console.log(x);
var x = 5;
console.log(x);
Javascript
console.log(x); var x = 5; console.log(x);
Attempts:
2 left
💡 Hint
Think about how var variables are hoisted but not initialized.
✗ Incorrect
Variables declared with var are hoisted to the top of their scope but initialized with undefined until the assignment line runs. So the first console.log prints undefined, the second prints 5.
❓ Predict Output
intermediate2:00remaining
var variable scope inside function
What will be the output of this code?
function test() {
var a = 10;
if (true) {
var a = 20;
console.log(a);
}
console.log(a);
}
test();Javascript
function test() { var a = 10; if (true) { var a = 20; console.log(a); } console.log(a); } test();
Attempts:
2 left
💡 Hint
Remember var is function scoped, not block scoped.
✗ Incorrect
The var declaration inside the if block overwrites the function scoped variable a. So both console.logs print 20.
❓ Predict Output
advanced2:00remaining
var redeclaration behavior
What is the output of this code?
var x = 1;
var x = 2;
console.log(x);
Javascript
var x = 1; var x = 2; console.log(x);
Attempts:
2 left
💡 Hint
var allows redeclaration without error.
✗ Incorrect
Redeclaring a var variable simply overwrites the previous value. So x becomes 2.
❓ Predict Output
advanced2:00remaining
var variable in loops and closures
What will this code print?
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs.push(function() { return i; });
}
console.log(funcs[0]());
console.log(funcs[1]());
console.log(funcs[2]());
Javascript
var funcs = []; for (var i = 0; i < 3; i++) { funcs.push(function() { return i; }); } console.log(funcs[0]()); console.log(funcs[1]()); console.log(funcs[2]());
Attempts:
2 left
💡 Hint
var is function scoped, so all functions share the same i.
✗ Incorrect
The variable i is shared in the loop and after the loop ends i is 3. All functions return 3.
🧠 Conceptual
expert2:00remaining
var variable redeclaration and hoisting combined
Consider this code snippet:
What will be the output when this code runs?
console.log(a);
var a = 10;
var a = 20;
console.log(a);
What will be the output when this code runs?
Javascript
console.log(a); var a = 10; var a = 20; console.log(a);
Attempts:
2 left
💡 Hint
var declarations are hoisted and redeclarations overwrite previous values.
✗ Incorrect
The first console.log prints undefined because a is hoisted but not initialized yet. The redeclaration does not cause error and the last assignment sets a to 20, so second console.log prints 20.