Conditionals: `if` statements

Now that we know about comparison operators, we can introduce if statements.

An if statement is used to make the program take a route, or another, depending on the result of the evaluation of an expression.

This is the simplest example, which always executes:

if (true) {
  //do something
}

on the contrary, this is never executed:

if (false) {
  //do something (? never ?)
}

The conditional checks the expression you pass to it for true or false value. If you pass a number, that always evaluates to true unless it’s 0. If you pass a string, it always evaluates to true unless it’s an empty string. Those are general rules of casting types to a boolean.

Did you notice the curly braces? That is called a block, and it is used to group a list of different statements.

A block can be put wherever you can have a single statement. And if you have a single statement to execute after the conditionals, you can omit the block, and just write the statement:

if (true) doSomething()

But I always like to use curly braces to be more clear.

Lessons in this unit:

0: Introduction
1: Comparison operators
2: ▶︎ `if` statements
3: How to use `else`
4: `switch`
5: The ternary operator
Want to learn more? Check out our courses