Truthiness narrowing in Typescript - Time & Space 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?
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 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.
As the number of values grows, the program checks each one once to see if it is truthy.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks and possible prints |
| 100 | About 100 checks and possible prints |
| 1000 | About 1000 checks and possible prints |
Pattern observation: The number of steps grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items to check.
[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.
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.
"What if we added a nested loop inside the truthiness check? How would the time complexity change?"