Equality and truthiness
Concept and syntax
Truthiness excludes values such as zero, empty text, false, null and undefined. If only absence is invalid, use an explicit equality comparison instead. A check such as x !== undefined preserves zero, whereas if (x) does not. Equality can also narrow common literal alternatives.
Working example
Save each snippet separately as main.ts in a fresh directory. Compile with tsc --strict --target ES2022 --module commonjs --moduleDetection force --skipLibCheck --noEmitOnError main.ts, then run the accepted example with node main.js. Forced module detection isolates snippet names from global declarations.
function value(x:number|undefined){ return x === undefined ? -1 : x; }console.log(value(0),value(undefined),value(8));Expected output:
0 -1 8Common mistake
Intentionally invalid; compile separately and do not execute.
function value(x:number|undefined){ return x.toFixed(1); }Expected diagnostic: TS18048. x may be undefined. Check it explicitly rather than discarding zero.
Practice and recap
Compare if (x) with x !== undefined for zero and eight.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Equality and truthiness — knowledge check
Check the contract, trace output, and diagnose an invalid example.
Which statement about this lesson’s concept is accurate?
What is the complete stdout, represented as a JSON string (including newline characters)?
function value(x:number|undefined){ return x === undefined ? -1 : x; }console.log(value(0),value(undefined),value(8));Which diagnostic and explanation match the rejected example under the lesson settings?
function value(x:number|undefined){ return x.toFixed(1); }