0
0
Javascriptprogramming~20 mins

Variable declaration using var in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Var Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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);
Aundefined\n5
Bundefined\nundefined
C5\n5
DReferenceError: x is not defined
Attempts:
2 left
💡 Hint
Think about how var variables are hoisted but not initialized.
Predict Output
intermediate
2: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();
A10\n20
B20\n20
C20\n10
DReferenceError
Attempts:
2 left
💡 Hint
Remember var is function scoped, not block scoped.
Predict Output
advanced
2: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);
ASyntaxError
B1
C2
DReferenceError
Attempts:
2 left
💡 Hint
var allows redeclaration without error.
Predict Output
advanced
2: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]());
AReferenceError
B0\n1\n2
Cundefined\nundefined\nundefined
D3\n3\n3
Attempts:
2 left
💡 Hint
var is function scoped, so all functions share the same i.
🧠 Conceptual
expert
2:00remaining
var variable redeclaration and hoisting combined
Consider this code snippet:
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);
Aundefined\n20
B10\n20
CReferenceError\n20
Dundefined\n10
Attempts:
2 left
💡 Hint
var declarations are hoisted and redeclarations overwrite previous values.