0
0
Typescriptprogramming~5 mins

Truthiness narrowing in Typescript - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Truthiness narrowing
O(n)
Understanding Time Complexity

We want to see how the time it takes to run code changes when we use truthiness checks to narrow types in TypeScript.

How does checking if a value is "truthy" affect how many steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function processValues(values: (string | null | undefined)[]) {
  for (const value of values) {
    if (value) {
      console.log(value.toUpperCase());
    }
  }
}
    

This code loops through an array and prints the uppercase version of each value only if it is truthy (not null or undefined).

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each element in the array once.
  • How many times: Exactly once per element, so as many times as the array length.
How Execution Grows With Input

As the number of values grows, the program checks each one once to see if it is truthy.

Input Size (n)Approx. Operations
10About 10 checks and possible prints
100About 100 checks and possible prints
1000About 1000 checks and possible prints

Pattern observation: The number of steps 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 with the number of items to check.

Common Mistake

[X] Wrong: "Checking truthiness inside the loop makes the code slower than looping alone."

[OK] Correct: The truthiness check is a simple step done once per item, so it doesn't add extra loops or nested work. It stays proportional to the input size.

Interview Connect

Understanding how simple checks inside loops affect performance helps you write clear and efficient code, a skill valued in many coding challenges and real projects.

Self-Check

"What if we added a nested loop inside the truthiness check? How would the time complexity change?"