Why JavaScript is widely used - Performance Analysis
We want to understand how the time it takes to run JavaScript code changes as the amount of work grows.
This helps us see why JavaScript works well for many tasks on the web.
Analyze the time complexity of the following code snippet.
function printNumbers(n) {
for (let i = 1; i <= n; i++) {
console.log(i);
}
}
printNumbers(5);
This code prints numbers from 1 up to n, showing a simple example of JavaScript doing repeated work.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop that prints each number.
- How many times: It runs once for each number from 1 to n.
As n grows, the number of times the loop runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 times |
| 100 | 100 times |
| 1000 | 1000 times |
Pattern observation: The work grows directly with the input size. Double the input, double the work.
Time Complexity: O(n)
This means the time to run the code grows in a straight line with the input size.
[X] Wrong: "JavaScript is slow because it always does too much work."
[OK] Correct: JavaScript can run simple loops like this efficiently, and the work grows only as needed with input size.
Understanding how JavaScript handles repeated tasks helps you explain why it is a popular choice for web development and how to write efficient code.
"What if we added a nested loop inside the first loop? How would the time complexity change?"