Challenge - 5 Problems
Function Scope Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
β Predict Output
intermediate2: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);
Attempts:
2 left
π‘ Hint
Variables declared inside a function are not accessible outside it.
β Incorrect
The variable 'message' is declared inside the function 'test', so it is only accessible there. The first console.log prints 'Hello'. The second console.log tries to access 'message' outside its scope, causing a ReferenceError.
β Predict Output
intermediate2: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();
Attempts:
2 left
π‘ Hint
Inner functions can access variables from their outer functions.
β Incorrect
The inner function can see the variable 'count' declared in the outer function, so it prints 5.
β Predict Output
advanced2: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();
Attempts:
2 left
π‘ Hint
Variables declared with var are function-scoped, not block-scoped.
β Incorrect
The variable 'x' declared with var inside the if block is accessible throughout the function, so console.log prints 10.
β Predict Output
advanced2:00remaining
Output with let inside block scope
What will this code output?
Javascript
function test() { if (true) { let y = 20; } console.log(y); } test();
Attempts:
2 left
π‘ Hint
Variables declared with let are block-scoped.
β Incorrect
The variable 'y' is declared inside the if block with let, so it is not accessible outside that block, causing a ReferenceError.
β Predict Output
expert3: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);
Attempts:
2 left
π‘ Hint
var is function-scoped and the loop variable is shared across all closures.
β Incorrect
All functions share the same 'i' variable, which after the loop ends is 3. So each function returns 3.