โ† flaviocopes.com

The JavaScript if/else conditional

Published Jun 01 2019

Psssst! The 2023 WEB DEVELOPMENT BOOTCAMP is starting on FEBRUARY 01, 2023! SIGNUPS ARE NOW OPEN to this 10-weeks cohort course. Learn the fundamentals, HTML, CSS, JS, Tailwind, React, Next.js and much more! โœจ

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

This is the simplest example, which always executes:

if (true) {
  //do something
}

on the contrary, this is never executed:

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

If you have a single statement to execute after the conditionals, you can omit the block, and just write the statement:

if (true) doSomething()

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.

Else

You can provide a second part to the if statement: else.

You attach a statement that is going to be executed if the if condition is false:

if (true) {
  //do something
} else {
  //do something else
}

Since else accepts a statement, you can nest another if/else statement inside it:

if (a === true) {
  //do something
} else if (b === true) {
  //do something else
} else {
  //fallback
}


I write books for developers ๐Ÿ‘‡๐Ÿผ

© 2023 Flavio Copes Flavio Copes made in Italy ๐Ÿ‡ฎ๐Ÿ‡น using Notion to Site Notion to Site