0
0
Javascriptprogramming~5 mins

Template literals in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Template literals
O(n²)
Understanding Time Complexity

We want to understand how the time it takes to create strings using template literals changes as the input grows.

Specifically, how does the work grow when we build strings with many parts?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const parts = ["Hello", "world", "this", "is", "template", "literals"];
let message = "";
for (let i = 0; i < parts.length; i++) {
  message = `${message} ${parts[i]}`;
}
console.log(message);
    

This code builds a message by adding each word from an array into a string using template literals inside a loop.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through the array and creating a new string each time by combining the old string with a new word.
  • How many times: The loop runs once for each word in the array (n times).
How Execution Grows With Input

Each time we add a word, the string gets longer, so combining takes more work.

Input Size (n)Approx. Operations
10About 55 string operations
100About 5050 string operations
1000About 500,500 string operations

Pattern observation: The work grows much faster than the number of words because each new string is longer than before.

Final Time Complexity

Time Complexity: O(n²)

This means the time to build the string grows roughly with the square of the number of words.

Common Mistake

[X] Wrong: "Adding words with template literals inside a loop always takes time proportional to the number of words (O(n))."

[OK] Correct: Each new string is longer, so combining strings inside the loop takes more and more time, making the total time grow faster than just the number of words.

Interview Connect

Understanding how string building grows with input size helps you write efficient code and explain your choices clearly in interviews.

Self-Check

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