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
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. Launching May 21, 2024. Join the waiting list!