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 the condition is true
, the if
block executes. if false
, the else
block executes. For multiple conditions,
use else if
:
To evaluate conditions, JavaScript uses comparison operators and truthy/falsy values.
Comparison Operators
- Greater than
>
or greater than or equal to>=
- Less than
<
or less than or equal to<=
- Strictly equal
===
or equal==
- Strictly unequal
!==
or unequal!=
Example:
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:
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.