if
An if runs a block of code only when its condition is true.
if is the basic way to make a decision in JavaScript. You write if, a condition in parentheses, and a block in curly braces. If the condition is true, the block runs. If not, JavaScript skips it and moves on to the next line.
The condition does not have to be a boolean. JavaScript converts the value to true or false: 0, "", null, undefined and NaN count as false. That is why clear conditions, like a comparison, are a good habit.
In the course you see it when validating data, for example if (Number.isNaN(age)) { in lesson 01.00: if the age is not a number, you handle the bad case before going on. Inside the block, TypeScript can also narrow a value's type. The type checker does that; when Node runs the code, the types are gone.
Reach for it when: part of your code should only run under a certain condition, like checking a value before you use it.
Examples
Common mistake
const name = "";
if (name) {
console.log("has name");
} else {
console.log("no name");
}
const count = 0;
if (count) {
console.log("has items");
} else {
console.log("no items");
}Why: An empty string and 0 are falsy. If 0 is a valid value for you, the condition treats it as missing.
How to write it: Compare explicitly, for example count !== undefined or count > 0.
Common mistake
let n: number = 5;
if (n = 10) {
console.log("ten");
}Why: A single = assigns instead of comparing. TypeScript allows this because the assignment returns the assigned value, which is then evaluated as truthy.
How to write it: Use === to compare: if (n === 10).
