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?"
Practice
if statement?Solution
Step 1: Understand what truthiness means
Truthiness means a value is considered true in a boolean context, so it is not null, undefined, 0, empty string, or false.Step 2: Apply truthiness narrowing in TypeScript
Inside anifstatement, TypeScript narrows the type by excluding falsy values, letting you safely use the value without extra checks.Final Answer:
It tells TypeScript the value is not null, undefined, or falsy, so you can use it safely. -> Option CQuick Check:
Truthiness narrowing = safe value use [OK]
- Thinking it converts values to strings
- Believing it skips type checks
- Assuming it improves runtime speed
if statements correctly uses truthiness narrowing?Solution
Step 1: Check each if condition for truthiness narrowing
if (value !== null && value !== undefined) { console.log(value); } explicitly checks for not null and not undefined, which is a common way to narrow truthy values.Step 2: Identify incorrect syntax or logic
if (value == false) { console.log(value); } checks if value is false (falsy), which is opposite of truthiness narrowing. if (value = true) { console.log(value); } uses assignment (=) instead of comparison (===). if (value === 0) { console.log(value); } checks if value equals 0, which is falsy, so it does not narrow to truthy.Final Answer:
if (value !== null && value !== undefined) { console.log(value); } -> Option DQuick Check:
Correct syntax and logic = if (value !== null && value !== undefined) { console.log(value); } [OK]
- Using assignment (=) instead of comparison (===)
- Checking for falsy instead of truthy
- Confusing equality operators
function printLength(str?: string) {
if (str) {
console.log(str.length);
} else {
console.log('No string');
}
}
printLength('hello');
printLength('');
printLength();Solution
Step 1: Analyze the if condition with truthiness narrowing
The conditionif (str)is true only if str is truthy. An empty string ('') is falsy, so it goes to else.Step 2: Check each function call output
printLength('hello') prints 5 because 'hello' is truthy and length is 5.
printLength('') prints 'No string' because '' is falsy.
printLength() prints 'No string' because str is undefined (falsy).Final Answer:
5, No string, No string -> Option AQuick Check:
Falsy empty string triggers else [OK]
- Assuming empty string is truthy
- Expecting undefined to print length
- Confusing falsy values with null only
function process(value: string | null) {
if (value !== null) {
console.log(value.toUpperCase());
} else {
console.log('No value');
}
}
process(null);
process(undefined);Solution
Step 1: Check the type of value and condition
Value can be string or null, but the function is called with undefined, which is not handled.Step 2: Identify missing check for undefined
The if condition only excludes null, so if value is undefined, it will cause an error when calling toUpperCase.Final Answer:
The if condition should check for undefined as well as null. -> Option AQuick Check:
Check all falsy types to avoid errors [OK]
- Ignoring undefined values
- Assuming null check covers undefined
- Not testing all input cases
input to avoid errors when accessing input.length?function handleInput(input: string | null | undefined | number) {
if (/* condition here */) {
console.log(input.length);
} else {
console.log('Invalid input');
}
}Solution
Step 1: Identify all possible types of input
Input can be string, null, undefined, or number. Only strings have a length property.Step 2: Narrow input to string and check truthiness
Usingtypeof input === 'string'ensures input is a string type. Adding&& inputexcludes empty strings (falsy) if needed.Final Answer:
if (typeof input === 'string' && input) { console.log(input.length); } -> Option BQuick Check:
Check type and truthiness for safe property access [OK]
- Only checking truthiness without type
- Ignoring number type causing errors
- Assuming null check covers undefined
Ready to prove it?
Pass the test and this pattern moves unknown
