skip to content
Dev Journal

If / Else Statements

/ 2 min read

Imagine you’re walking on a busy street and the pedestrian light turns red. You stop, right? When it turns green, you start walking again. This can be translated into code as: “If the light is red, stop walking. Otherwise, keep walking.” This is the essence of an if/else statement.

The if/else statement

An if/else statement controls what your program does in specific situations, also known as a control flow statement. It looks like this:

if (condition) {
// Do something
} else {
// Do something else
}

if the condition is true, the if block executes. if false, the else block executes. For multiple conditions, use else if:

if (light === 'red') {
// Stop walking
} else if (cars.around) {
// Stop walking
} else {
// Continue walking
}

To evaluate conditions, JavaScript uses comparison operators and truthy/falsy values.

Comparison Operators

  1. Greater than > or greater than or equal to >=
  2. Less than < or less than or equal to <=
  3. Strictly equal === or equal ==
  4. Strictly unequal !== or unequal !=

Example:

24 > 23 // True
// Strictly equal
'24' === 24 // False
// Equal
'24' == 24 // True

Always ise strict versions === or !== to avoid type conversion issues.

Truthy and Falsy Values

  • Falsy values are false, undefined, null, 0, "", NaN.
  • Truthy values are anything above.

Example:

const numApples = 135
if (numApples) {
// Eat an apple
} else {
// Buy an apple
}

Summary

An if/else statement controls program flow based on conditions. it uses comparison operators to evaluate these conditions and relies on truthy/falsy values for decision-making. Always use strict comparison operators to avoid unexpected type conversions.