0
0
Javascriptprogramming~5 mins

String concatenation in output in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: String concatenation in output
O(n²)
Understanding Time Complexity

When we join strings together in JavaScript, the time it takes can change depending on how many strings we combine.

We want to know how the work grows as we add more strings to join.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


let result = "";
const words = ["hello", "world", "this", "is", "fun"];
for (let i = 0; i < words.length; i++) {
  result += words[i];
}
console.log(result);
    

This code joins all words in the array into one string by adding each word one by one.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Adding each word to the growing string inside the loop.
  • How many times: Once for each word in the array.
How Execution Grows With Input

Each time we add a new word, the string gets longer, so adding takes more work than before.

Input Size (n)Approx. Operations
10About 55 steps
100About 5,050 steps
1000About 500,500 steps

Pattern observation: The work grows much faster than the number of words because each addition copies the whole string so far.

Final Time Complexity

Time Complexity: O(n²)

This means the time to join strings grows roughly with the square of the number of words.

Common Mistake

[X] Wrong: "Adding strings in a loop always takes time proportional to the number of strings (O(n))."

[OK] Correct: Each addition copies the entire string so far, so the work adds up much faster than just counting words.

Interview Connect

Understanding how string joining works helps you write faster code and shows you think about how programs grow with input size.

Self-Check

"What if we used an array to collect words first and joined them all at once at the end? How would the time complexity change?"