0
0
Javascriptprogramming~20 mins

Function scope in Javascript - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
πŸŽ–οΈ
Function Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of variable inside function scope
What will be the output of the following code?
Javascript
function test() {
  let message = "Hello";
  console.log(message);
}
test();
console.log(message);
AHello\nReferenceError
BHello\nundefined
Cundefined\nHello
DReferenceError\nHello
Attempts:
2 left
πŸ’‘ Hint
Variables declared inside a function are not accessible outside it.
❓ Predict Output
intermediate
2:00remaining
Output of nested function accessing outer variable
What will this code print to the console?
Javascript
function outer() {
  let count = 5;
  function inner() {
    console.log(count);
  }
  inner();
}
outer();
Aundefined
B5
CReferenceError
D0
Attempts:
2 left
πŸ’‘ Hint
Inner functions can access variables from their outer functions.
❓ Predict Output
advanced
2:00remaining
Effect of var in function scope
What is the output of this code?
Javascript
function example() {
  if (true) {
    var x = 10;
  }
  console.log(x);
}
example();
A10
BReferenceError
Cundefined
DTypeError
Attempts:
2 left
πŸ’‘ Hint
Variables declared with var are function-scoped, not block-scoped.
❓ Predict Output
advanced
2:00remaining
Output with let inside block scope
What will this code output?
Javascript
function test() {
  if (true) {
    let y = 20;
  }
  console.log(y);
}
test();
A20
BTypeError
CReferenceError
Dundefined
Attempts:
2 left
πŸ’‘ Hint
Variables declared with let are block-scoped.
❓ Predict Output
expert
3:00remaining
Output of closures with loop and var
What will be the output of this code when calling all functions in the array?
Javascript
function createFunctions() {
  var funcs = [];
  for (var i = 0; i < 3; i++) {
    funcs.push(function() {
      return i;
    });
  }
  return funcs;
}
const functions = createFunctions();
const results = functions.map(f => f());
console.log(results);
A[0, 1, 2]
B[0, 0, 0]
C[undefined, undefined, undefined]
D[3, 3, 3]
Attempts:
2 left
πŸ’‘ Hint
var is function-scoped and the loop variable is shared across all closures.