Conditionals
-
Comparisions
-
Conditional Statements
if
if (hour < 18) { greeting = "Good day"; }
else
if (hour < 18) { greeting = "Good day"; } else { greeting = "Good evening"; }
else if
if (time < 10) { greeting = "Good morning"; } else if (time < 20) { greeting = "Good day"; } else { greeting = "Good evening"; }
-
Logical operators
-
|| (OR)
- There are four possible logical combinations:
alert( true || true ); // true alert( false || true ); // true alert( true || false ); // true alert( false || false ); // false
- In other words,
OR
returns the first truthy value it finds.
- There are four possible logical combinations:
-
&& (AND)
- AND returns
true
if both operands are truthy andfalse
otherwise. - Given multiple AND’ed values, the AND
&&
operator does the following:- Evaluates operands from left to right.
- For each operand, converts it to a boolean. If the result is false, stops and returns the original value of that operand.
- If all operands have been evaluated (i.e. all were truthy), returns the last operand.
- In other words,
AND
returns the first falsy value or the last value if none were found in case of multiple AND’ed. - We can also pass several values in a row. See how the first falsy one is returned:
alert( 1 && 2 && null && 3 ); // null
- When all values are truthy, the last value is returned:
alert( 1 && 2 && 3 ); // 3, the last one
- Precedence of AND
&&
is higher than OR||
.
- AND returns
-
! (NOT)
- The operator accepts a single argument and does the following:
- Converts the operand to boolean type:
true/false
. - Returns the inverse value.
alert( !true ); // false alert( !0 ); // true
- Converts the operand to boolean type:
- A double NOT
!!
is sometimes used for converting a value to boolean type. That is, the first NOT converts the value to boolean and returns the inverse, and the second NOT inverses it again. In the end, we have a plain value-to-boolean conversion.alert( !!"non-empty string" ); // true alert( !!null ); // false
- We can use a built-in
Boolean
function to do the same.
- The operator accepts a single argument and does the following:
-
-
Ternary operator
condition ? run this code : run this code instead
-
const greeting = isBirthday ? "Happy birthday Mrs. Smith — we hope you have a great day!" : "Good morning Mrs. Smith.";
- Here we have a variable called
isBirthday
— if this istrue
, we give our guest a happy birthday message; if not, we give her the standard daily greeting.
-
Switch
-
switch (expression) { case x: // execute case x code block break; case y: // execute case y code block break; default: // execute default code block }
-