Function hoisting behavior in Javascript - Time & Space 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?
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 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.
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 |
|---|---|
| 10 | 2 function calls |
| 100 | 2 function calls |
| 1000 | 2 function calls |
Pattern observation: The number of operations stays the same no matter how big the input is.
Time Complexity: O(1)
This means the time to run the code stays constant and does not increase with input size.
[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.
Understanding how JavaScript handles functions helps you write clearer code and explain behavior confidently in interviews.
"What if we replaced the function expression with an arrow function assigned to a variable? How would the time complexity change?"