0
0
Javascriptprogramming~5 mins

Logical operators in Javascript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Logical operators
O(n)
Understanding Time Complexity

Logical operators combine true or false values to make decisions in code.

We want to see how the time to run code changes when using these operators.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function checkValues(arr) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] && arr[i].isActive) {
      console.log('Active item found');
    }
  }
}
    

This code checks each item in an array to see if it exists and is active.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element of the array.
  • How many times: Once for every item in the array.
How Execution Grows With Input

As the array gets bigger, the code checks more items one by one.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The number of checks grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Logical operators make the code run faster because they skip some checks."

[OK] Correct: Logical operators do short-circuit, but the loop still runs once per item, so time grows with input size.

Interview Connect

Understanding how logical operators affect loops helps you explain code efficiency clearly and confidently.

Self-Check

"What if we replaced the loop with a recursive function? How would the time complexity change?"