0
0
Javascriptprogramming~5 mins

Primitive data types in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Primitive data types
O(1)
Understanding Time Complexity

We want to understand how fast operations on primitive data types run in JavaScript.

How does the time to work with these simple values change as we use more or bigger data?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


const a = 5;
const b = 'hello';
const c = true;

const sum = a + 10;
const greeting = b + ' world';
const isFalse = !c;

console.log(sum, greeting, isFalse);
    

This code uses simple operations on primitive data types: numbers, strings, and booleans.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Simple arithmetic and string concatenation on primitive values.
  • How many times: Each operation runs once, no loops or repeated traversals.
How Execution Grows With Input

Operations on primitive types happen instantly and do not grow with input size here.

Input Size (n)Approx. Operations
103
1003
10003

Pattern observation: The number of operations stays the same no matter how big the input is.

Final Time Complexity

Time Complexity: O(1)

This means the time to do these operations stays constant, no matter the input size.

Common Mistake

[X] Wrong: "String concatenation always takes longer as strings get bigger."

[OK] Correct: In JavaScript, simple concatenation of small strings is very fast and treated as a single step here; only very large strings or repeated concatenations in loops cause noticeable time growth.

Interview Connect

Understanding that primitive operations run in constant time helps you explain why some code is fast and others slow, a key skill in coding interviews.

Self-Check

"What if we replaced string concatenation with joining an array of 1000 strings? How would the time complexity change?"