JavaScriptLesson 5 of 18

JavaScript Conditions

Conditions let your code make decisions. You ask a question, and the program takes one path when the answer is true and another when it is false. The JavaScript if statement is the main tool for this, and it reads almost like plain English, which is why it is the first decision tool every beginner learns.

Conditions let your code make decisions. You ask a question, and the program takes one path when the answer is true and another when it is false. The JavaScript if statement is the main tool for this, and it reads almost like plain English, which is why it is the first decision tool every beginner learns.

Write if, then a condition in parentheses, then a block in curly braces. If the condition is true, the block runs. Add else to run something when the condition is false, and else if to ask a second question. You can chain many else if blocks, and the browser checks them in order, stopping at the first true one.

Here is the part most beginners miss: the condition does not have to be a comparison. JavaScript treats some values as false and everything else as true. The falsy values are 0, "", null, undefined, NaN, and false. Everything else is truthy, so an empty string fails the check but any text passes it. That is handy for checking whether an input has content.

The if else pattern

The two-way pattern is the most common. One branch runs when the condition is true, the other for everything else. Exactly one branch runs, never both, which keeps the outcome predictable.

JS
if (score >= 90) {
  grade = "A";
} else {
  grade = "B";
}

Chaining conditions

For more than two choices, add else if blocks. The browser checks each in order and stops at the first true condition. The final else catches everything left over, and it is optional. A common mistake is checking overlapping ranges in the wrong order.

JS
if (age < 13) {
  ticket = "child";
} else if (age < 65) {
  ticket = "adult";
} else {
  ticket = "senior";
}

Syntax

JS
if (age >= 18) {
  console.log("You can vote");
} else {
  console.log("Too young to vote");
}

if("0") Is True, if(0) Is False

Empty string, 0, null, undefined, NaN are falsy — "0" is truthy! Check explicitly.

JS
if (input.trim() === "") // not if(input)

Good to know

  • if runs a block when the condition is true; else covers the rest.
  • else if lets you ask more than one question in order.
  • 0, "", null, undefined, NaN, and false are the falsy values.
  • A single = assigns a value; === compares, so never confuse them.
Try it Yourself Edit the code, press Run, then check what changed in the Result.
Ready
Code
Result

Practice makes it stick

Open the Playground and build your own page with the tags you just learned.

→ Open Playground