What is JavaScript - Complexity Analysis
JavaScript is a programming language used to make web pages interactive. When we write JavaScript code, it runs step by step to do tasks.
We want to understand how the time it takes to run JavaScript code changes as the work it does grows.
Analyze the time complexity of the following code snippet.
function greet(name) {
console.log('Hello, ' + name + '!');
}
greet('Alice');
This code prints a greeting message once for a given name.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Printing one message to the console.
- How many times: Exactly once per function call.
Explain the growth pattern intuitively.
| Input Size (n) | Approx. Operations |
|---|---|
| 1 | 1 |
| 10 | 1 |
| 100 | 1 |
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 does not grow with input size; it stays constant.
[X] Wrong: "The time to greet someone grows with the length of their name."
[OK] Correct: Printing a message happens once regardless of name length, so time stays the same.
Understanding simple time complexity like this builds your confidence to analyze bigger, more complex code pieces.
"What if we changed the function to greet an array of names instead of one? How would the time complexity change?"