0
0
Javascriptprogramming~5 mins

Function hoisting behavior in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function hoisting behavior
O(1)
Understanding Time Complexity

We want to understand how the order of function declarations affects the time it takes for JavaScript to run code.

Specifically, does calling a function before it is written change how long the program takes to run?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function greet() {
  return "Hello!";
}

console.log(greet());

const sayBye = function() {
  return "Goodbye!";
};

console.log(sayBye());
    

This code calls two functions: one declared normally and one assigned to a variable.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: There are no loops or repeated operations here; each function is called once.
  • How many times: Each function runs exactly one time.
How Execution Grows With Input

Since there are no loops or repeated calls, the time to run this code does not grow with input size.

Input Size (n)Approx. Operations
102 function calls
1002 function calls
10002 function calls

Pattern observation: The number of operations stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to run the code stays constant and does not increase with input size.

Common Mistake

[X] Wrong: "Calling a function before it is declared always slows down the program."

[OK] Correct: JavaScript moves function declarations to the top before running code, so calling them early does not add extra time.

Interview Connect

Understanding how JavaScript handles functions helps you write clearer code and explain behavior confidently in interviews.

Self-Check

"What if we replaced the function expression with an arrow function assigned to a variable? How would the time complexity change?"