Conditionals

if

The if statement executes some code if a specified condition is true.

if (true) {
  console.log("this will be printed");
}

if (false) {
  console.log("this will not be printed");
}

var x = 4;
//var x = 5;
if (x === 5) {
  console.log("x equals 5");
}

if/else

When we want code that executes when the if statement condition is false, we can use the else keyword as a shorthand.

var isTasty;
var food = "vegetables";
//var food = "pizza";
if (food === "pizza") {
  isTasty = true;
} else {
  isTasty = false;
}
console.log("Is the food tasty?", isTasty);

if/else if/else

switch

Sometimes, numerous if/else statements make code hard to read. There's an alternative called a switch statement. It accepts a value and compares the value against various cases.

Each case block must end with break;, otherwise the block will fall through to the next block. If none of the cases match the value, you can also implement a default case.

Exercise:

Rewrite the if/else if/else example above using a switch statement.

Switch statements can evaluate inequalities too!

Truthy vs. Falsey

What happens if we put something other than a Boolean as the conditional in an if statement? Turns out, any value can be evaluated as true or false.

Most values are truthy. In fact, there are only 6 falsey values in Javascript - can you guess them all?

More on this topic: http://james.padolsey.com/javascript/truthy-falsey/

Last updated

Was this helpful?