Summary of “Conditions”

Syntax

Condition:

if (condition) {
  action;
}

Condition with alternative action:

if (condition) {
  actions;
} else {
  other actions;
}

Nested conditions:

if (condition1) {
  if (condition2) {
    actions;
  }
}

How Conditions Work

The if statement tests the value of the expression in parentheses as a Boolean. The action inside the if block is executed if that value is true. If the value is false, the action will not be executed.

Code inside the checks

Comparison operators:

OperatorName
>greater than
<less than
>=greater than or equal to
<=less than or equal to

Equality operators:

OperatorNameDescription
==loose equalitywith type conversion
===strict equalitywithout type conversion
!=loose inequalitywith type conversion
!==strict inequalitywithout type conversion

The value used as a condition is tested as a Boolean. Of the numbers used here, all except 0 are converted to true, and 0 is converted to false. All strings except the empty string are converted to true; the empty string '' is converted to false. The value undefined is also converted to false.

Logical operators.

  • For Boolean values, the && operator or “logical AND” returns true only when both values, to the left and right of it, are true.
  • For Boolean values, the || operator or “logical OR” returns true when at least one value, to the left or right of it, is true.
  • The ! operator or “logical negation” changes the Boolean value of the expression to the right of it to the opposite value.

Continue