0
0
Javascriptprogramming~5 mins

Writing first JavaScript program - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Writing first JavaScript program
O(1)
Understanding Time 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.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


console.log('Hello, world!');
    

This code simply prints a message once to the screen.

Identify Repeating Operations

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.
How Execution Grows With Input

Explain the growth pattern intuitively.

Input Size (n)Approx. Operations
11 print
101 print
1001 print

Pattern observation: No matter how big the input is, the program only prints once, so the work stays the same.

Final Time Complexity

Time Complexity: O(1)

This means the program takes the same amount of time no matter how big the input is.

Common Mistake

[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.

Interview Connect

Understanding how simple programs run helps build a strong base for more complex coding tasks later on.

Self-Check

"What if we added a loop to print the message multiple times? How would the time complexity change?"