Writing first JavaScript program - Time & Space Complexity
When we write our first JavaScript program, it is important to see how the time it takes to run changes as we add more code or data.
We want to know how the program's work grows when we change its size or input.
Analyze the time complexity of the following code snippet.
console.log('Hello, world!');
This code simply prints a message once to the screen.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One single print to the console.
- How many times: Exactly once, no loops or repeats.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 print |
| 10 | 1 print |
| 100 | 1 print |
Pattern observation: No matter how big the input is, the program only prints once, so the work stays the same.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "Adding more data to the program will make it slower even if the code does not repeat."
[OK] Correct: If the program only does one action, like printing once, adding data that is not used does not change the time it takes.
Understanding how simple programs run helps build a strong base for more complex coding tasks later on.
"What if we added a loop to print the message multiple times? How would the time complexity change?"