Bird
Raised Fist0
Javascriptprogramming~10 mins

Function scope in Javascript - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Function scope
Enter function
↓
Create local variables
↓
Execute function body
↓
Access local variables inside function
↓
Exit function
↓
Local variables destroyed
↓
Try to access local variables outside? --> ReferenceError
When a function runs, it creates its own space for variables. These variables only exist inside the function and disappear when it ends.
Execution Sample
Javascript
function greet() {
  let message = 'Hello';
  console.log(message);
}
greet();
console.log(message);
This code shows a variable inside a function that cannot be used outside.
Execution Table
StepActionVariable 'message'OutputNotes
1Function greet() is definedundefinedNo variables created yet
2Call greet()undefinedEnter function scope
3Create local variable message = 'Hello''Hello'message exists only inside greet
4console.log(message)'Hello'HelloPrints 'Hello' inside function
5Function greet() endsundefinedLocal variable destroyed
6console.log(message) outsideundefinedReferenceErrormessage not defined outside function
💡 Function ends and local variables are removed; accessing them outside causes ReferenceError
Variable Tracker
VariableStartAfter Step 3After Step 5Final
messageundefined'Hello'undefinedundefined
Key Moments - 2 Insights
Why can't we use the variable 'message' outside the function?
Because 'message' is created inside the function and only exists there. After the function ends (see step 5), it is removed, so outside the function (step 6) it causes a ReferenceError.
Does the variable 'message' exist before the function is called?
No, 'message' is created only when the function runs (step 3). Before that, it is undefined.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'message' after step 3?
AReferenceError
B'Hello'
Cundefined
Dnull
💡 Hint
Check the 'Variable message' column at step 3 in the execution table.
At which step does the function 'greet' end and local variables get destroyed?
AStep 2
BStep 4
CStep 5
DStep 6
💡 Hint
Look at the 'Action' and 'Notes' columns for when the function ends.
If we move 'console.log(message)' inside the function after step 3, what will happen?
AIt will print 'Hello'
BIt will cause ReferenceError
CIt will print undefined
DIt will print null
💡 Hint
See step 4 where console.log(message) inside the function prints 'Hello'.
Concept Snapshot
Function scope means variables declared inside a function exist only there.
They are created when the function runs and destroyed when it ends.
Trying to access them outside causes a ReferenceError.
Use console.log inside the function to see local variables.
Variables outside functions are global and accessible everywhere.
Full Transcript
This visual shows how function scope works in JavaScript. When the function greet() is called, it creates a local variable message with value 'Hello'. This variable exists only inside the function. The console.log inside the function prints 'Hello'. After the function ends, the variable message is destroyed. Trying to access message outside the function causes a ReferenceError because it does not exist there. This shows that variables inside functions are private to that function and cannot be used outside.

Practice

(1/5)
1. What does function scope mean in JavaScript?
easy
A. Variables declared inside a function are only accessible within that function.
B. Variables declared inside a function are accessible everywhere in the program.
C. Functions can only be called inside other functions.
D. Variables declared outside a function are not accessible inside it.

Solution

  1. Step 1: Understand variable accessibility

    Variables declared inside a function are private to that function and cannot be accessed outside.
  2. Step 2: Compare options with this rule

    Only Variables declared inside a function are only accessible within that function. correctly states this behavior.
  3. Final Answer:

    Variables declared inside a function are only accessible within that function. -> Option A
  4. Quick Check:

    Function scope = variables inside function only [OK]
Hint: Remember: function variables stay inside the function [OK]
Common Mistakes:
  • Thinking variables inside functions are global
  • Confusing function scope with block scope
  • Assuming functions can't access outer variables
2. Which of the following is the correct way to declare a variable with function scope inside a function?
easy
A. if (true) { var x = 5; }
B. let x = 5;
C. function x = 5;
D. const x = 5;

Solution

  1. Step 1: Identify valid function-scoped declarations

    Inside a function, let, const, and var declare variables with function or block scope.
  2. Step 2: Check syntax correctness

    function x = 5; is invalid syntax. let x = 5; and const x = 5; use block scope. if (true) { var x = 5; } declares var with function scope, as it is hoisted to the function level.
  3. Final Answer:

    if (true) { var x = 5; } -> Option A
  4. Quick Check:

    Use const or let inside functions [OK]
Hint: Use var inside functions for function scope [OK]
Common Mistakes:
  • Using 'function' keyword to declare variables
  • Confusing block scope with function scope
  • Assuming var is block scoped
3. What will be the output of this code?
function test() {
  let a = 10;
  if (true) {
    let a = 20;
    console.log(a);
  }
  console.log(a);
}
test();
medium
A. 10\n10
B. 20\n20
C. 20\n10
D. ReferenceError

Solution

  1. Step 1: Understand variable shadowing inside blocks

    The inner let a = 20; creates a new variable scoped to the if-block, shadowing the outer a = 10.
  2. Step 2: Trace console.log outputs

    Inside the if-block, a is 20, so first log prints 20. Outside the block but inside the function, a is still 10, so second log prints 10.
  3. Final Answer:

    20 10 -> Option C
  4. Quick Check:

    Block scope shadows outer variable = 20 then 10 [OK]
Hint: Inner let shadows outer let inside blocks [OK]
Common Mistakes:
  • Assuming both logs print the same value
  • Confusing block scope with function scope
  • Expecting ReferenceError for inner variable
4. Find the error in this code:
function example() {
  console.log(x);
  let x = 5;
}
example();
medium
A. Outputs undefined
B. No error, outputs 5
C. SyntaxError due to missing semicolon
D. ReferenceError because x is used before declaration

Solution

  1. Step 1: Understand temporal dead zone with let

    Variables declared with let are not accessible before their declaration inside the function, causing a ReferenceError if accessed earlier.
  2. Step 2: Analyze the console.log usage

    The code tries to log x before it is declared with let x = 5;, causing a ReferenceError.
  3. Final Answer:

    ReferenceError because x is used before declaration -> Option D
  4. Quick Check:

    Accessing let before declaration = ReferenceError [OK]
Hint: Don't use let variables before declaring them [OK]
Common Mistakes:
  • Thinking var behaves the same as let here
  • Expecting undefined instead of error
  • Ignoring temporal dead zone rules
5. You want to create a function that counts how many times it has been called using function scope. Which code correctly does this?
function counter() {
  // Your code here
}
console.log(counter());
console.log(counter());
console.log(counter());
hard
A. function counter() { let count = 0; count++; return count; }
B. function counter() { if (!counter.count) counter.count = 0; counter.count++; return counter.count; }
C. let count = 0; function counter() { count++; return count; }
D. function counter() { const count = 0; count++; return count; }

Solution

  1. Step 1: Understand function scope and persistence

    Variables declared inside the function reset each call, so to keep count, it must be stored outside or as a property.
  2. Step 2: Analyze each option

    function counter() { let count = 0; count++; return count; } resets count to 0 every call, so always returns 1. function counter() { if (!counter.count) counter.count = 0; counter.count++; return counter.count; } uses a property on the function to store count, preserving it across calls. let count = 0; function counter() { count++; return count; } uses a global variable, which works but is not function scope. function counter() { const count = 0; count++; return count; } tries to increment a constant, causing error.
  3. Final Answer:

    function counter() { if (!counter.count) counter.count = 0; counter.count++; return counter.count; } -> Option B
  4. Quick Check:

    Use function property to store persistent count [OK]
Hint: Use function properties to keep data across calls [OK]
Common Mistakes:
  • Resetting count inside function each call
  • Using const and trying to increment
  • Using global variables instead of function scope
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard