Conditional Operators: If, '?'
Conditional Operators: If, '?'
To do that, we can use the if statement and the conditional operator ?, that’s also called a “question
mark” operator.
The if statement evaluates a condition and, if the condition’s result is true, executes a block of code.
For example:
let year = prompt('In which year was ECMAScript-2015 specification published?', '');
if (year == 2015) alert( 'You are right!' );
In the example above, the condition is a simple equality check (year == 2015), but it can be much
more complex.
If we want to execute more than one statement, we have to wrap our code block inside curly braces:
if (year == 2015) {
alert( "That's correct!" );
alert( "You're so smart!" );
}
We recommend wrapping your code block with curly braces {} every time you use an if statement,
even if there is only one statement to execute. Doing so improves readability.
Boolean conversion
The if (…) statement evaluates the expression in its parentheses and converts the result to a boolean.
Let’s recall the conversion rules from the chapter Type Conversions:
A number 0, an empty string "", null, undefined, and NaN all become false. Because of that
they are called “falsy” values.
Other values become true, so they are called “truthy”.
if (false) { // 0 is falsy
...
}
if (true) { // 1 is truthy
...
}
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 2 of 23
if (cond) {
...
}
The if statement may contain an optional “else” block. It executes when the condition is false.
For example:
let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
if (year == 2015) {
alert( 'You guessed it right!' );
} else {
alert( 'How can you be so wrong?' ); // any value except 2015
}
Sometimes, we’d like to test several variants of a condition. The else if clause lets us do that.
For example:
let year = prompt('In which year was the ECMAScript-2015 specification published?', '');
In the code above, JavaScript first checks year < 2015. If that is false, it goes to the next condition
year > 2015. If that is also false, it shows the last alert.
For instance:
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 3 of 23
let accessAllowed;
let age = prompt('How old are you?', '');
alert(accessAllowed);
The so-called “conditional” or “question mark” operator lets us do that in a shorter and simpler way.
The operator is represented by a question mark ?. Sometimes it’s called “ternary”, because the
operator has three operands. It is actually the one and only operator in JavaScript which has that
many.
The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2.
For example:
Technically, we can omit the parentheses around age > 18. The question mark operator has a low
precedence, so it executes after the comparison >.
But parentheses make the code more readable, so we recommend using them.
Please note:
In the example above, you can avoid using the question mark operator because the comparison itself
returns true/false:
// the same
let accessAllowed = age > 18;
Multiple ‘?’
A sequence of question mark operators ? can return a value that depends on more than one condition.
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 4 of 23
For instance:
alert( message );
It may be difficult at first to grasp what’s going on. But after a closer look, we can see that it’s just an
ordinary sequence of tests:
if (age < 3) {
message = 'Hi, baby!';
} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
} else {
message = 'What an unusual age!';
}
Depending on the condition company == 'Netscape', either the first or the second expression after the
? gets executed and shows an alert.
We don’t assign a result to a variable here. Instead, we execute different code depending on the
condition.
Tasks
1. Will alert be shown?
if ("0") {
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 5 of 23
alert( 'Hello' );
}
2. Using the if..else construct, write the code which asks: ‘What is the “official” name of JavaScript?’
If the visitor enters “ECMAScript”, then output “Right!”, otherwise – output: “Didn’t know?
ECMAScript!”
3. Using if..else, write the code which gets a number via prompt and then shows in alert:
if (a + b < 4) {
result = 'Below';
} else {
result = 'Over';
}
For readability, it’s recommended to split the code into multiple lines.
let message;
if (login == 'Employee') {
message = 'Hello';
} else if (login == 'Director') {
message = 'Greetings';
} else if (login == '') {
message = 'No login';
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 6 of 23
} else {
message = '';
}
Logical operators
There are three logical operators in JavaScript: || (OR), && (AND), ! (NOT).
Although they are called “logical”, they can be applied to values of any type, not only boolean. Their
result can also be of any type.
|| (OR)
result = a || b;
In classical programming, the logical OR is meant to manipulate boolean values only. If any of its
arguments are true, it returns true, otherwise it returns false.
In JavaScript, the operator is a little bit trickier and more powerful. But first, let’s see what happens
with boolean values.
As we can see, the result is always true except for the case when both operands are false.
Most of the time, OR || is used in an if statement to test if any of the given conditions is true.
For example:
let hour = 9;
}
We can pass more conditions:
let hour = 12;
let isWeekend = true;
The logic described above is somewhat classical. Now, let’s bring in the “extra” features of
JavaScript.
In other words, a chain of OR "||" returns the first truthy value or the last one if no truthy value is
found.
For instance:
alert( 1 || 0 ); // 1 (1 is truthy)
alert( true || 'no matter what' ); // (true is truthy)
This leads to some interesting usage compared to a “pure, classical, boolean-only OR”.
Imagine we have a list of variables which can either contain data or be null/undefined. How
can we find the first one with data?
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 8 of 23
If both currentUser and defaultUser were false, "unnamed" would be the result.
2. Short-circuit evaluation.
Operands can be not only values, but arbitrary expressions. OR evaluates and tests them from
left to right. The evaluation stops when a truthy value is reached, and the value is returned.
This process is called “a short-circuit evaluation” because it goes as short as possible from
left to right.
This is clearly seen when the expression given as the second argument has a side effect like a
variable assignment.
let x;
true || (x = 1);
alert(x); // undefined, because (x = 1) not evaluated
If, instead, the first argument is false, || evaluates the second one, thus running the
assignment:
let x;
false || (x = 1);
alert(x); // 1
An assignment is a simple case. There may be side effects, that won’t show up if the
evaluation doesn’t reach them.
As we can see, such a use case is a "shorter way of doing if". The first operand is
converted to boolean. If it’s false, the second one is evaluated.
Most of time, it’s better to use a “regular” if to keep the code easy to understand, but
sometimes this can be handy.
&& (AND)
result = a && b;
In classical programming, AND returns true if both operands are truthy and false otherwise:
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 9 of 23
In other words, AND returns the first falsy value or the last value if none were found.
The rules above are similar to OR. The difference is that AND returns the first falsy value while OR
returns the first truthy one.
Examples:
We can also pass several values in a row. See how the first falsy one is returned:
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 10 of 23
So the code a && b || c && d is essentially the same as if the && expressions were in parentheses: (a
&& b) || (c && d).
Just like OR, the AND && operator can sometimes replace if.
For instance:
let x = 1;
(x > 0) && alert( 'Greater than zero!' );
The action in the right part of && would execute only if the evaluation reaches it. That is, only if (x
> 0) is true.
let x = 1;
if (x > 0) {
alert( 'Greater than zero!' );
}
The variant with && appears shorter. But if is more obvious and tends to be a little bit more
readable.
So we recommend using every construct for its purpose: use if if we want if and use && if we want
AND.
! (NOT)
result = !value;
For instance:
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.
There’s a little more verbose way to do the same thing – a built-in Boolean function:
The precedence of NOT ! is the highest of all logical operators, so it always executes first, before
&& or ||.
Tasks
1. What is the code below going to output?
alert( null || 2 || undefined );
The schema:
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 12 of 23
Please use nested if blocks. Mind the overall readability of the code.
Hint: passing an empty input to a prompt returns an empty string ''. Pressing ESC during a prompt
returns null.
For example, outputting goods from a list one after another or just running the same code for each
number from 1 to 10.
while (condition) {
// code
// so-called "loop body"
}
While the condition is true, the code from the loop body is executed.
let i = 0;
while (i < 3) { // shows 0, then 1, then 2
alert( i );
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 13 of 23
i++;
}
A single execution of the loop body is called an iteration. The loop in the example above makes
three iterations.
If i++ was missing from the example above, the loop would repeat (in theory) forever. In practice,
the browser provides ways to stop such loops, and in server-side JavaScript, we can kill the process.
Any expression or variable can be a loop condition, not just comparisons: the condition is evaluated
and converted to a boolean by while.
let i = 3;
while (i) { // when i becomes 0, the condition becomes falsy, and the loop stops
alert( i );
i--;
}
Curly braces are not required for a single-line body
If the loop body has a single statement, we can omit the curly braces {…}:
let i = 3;
while (i) alert(i--);
The condition check can be moved below the loop body using the do..while syntax:
do {
// loop body
} while (condition);
The loop will first execute the body, then check the condition, and, while it’s truthy, execute it again
and again.
For example:
let i = 0;
do {
alert( i );
i++;
} while (i < 3);
This form of syntax should only be used when you want the body of the loop to execute at least once
regardless of the condition being truthy. Usually, the other form is preferred: while(…) {…}.
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 14 of 23
Let’s learn the meaning of these parts by example. The loop below runs alert(i) for i from 0 up to
(but not including) 3:
If you are new to loops, it could help to go back to the example and reproduce how it runs step-by-
step on a piece of paper.
// run begin
let i = 0
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// if condition → run body and run step
if (i < 3) { alert(i); i++ }
// ...finish, because now i == 3
Here, the “counter” variable i is declared right in the loop. This is called an “inline” variable
declaration. Such variables are visible only inside the loop.
let i = 0;
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 15 of 23
Skipping parts
For example, we can omit begin if we don’t need to do anything at the loop start.
Like here:
let i = 0;
for (;;) {
// repeats without limits
}
Please note that the two for semicolons ; must be present. Otherwise, there would be a syntax error.
But we can force the exit at any time using the special break directive.
For example, the loop below asks the user for a series of numbers, “breaking” when no number is
entered:
let sum = 0;
while (true) {
let value = +prompt("Enter a number", '');
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 16 of 23
The break directive is activated at the line (*) if the user enters an empty line or cancels the input. It
stops the loop immediately, passing control to the first line after the loop. Namely, alert.
The combination “infinite loop + break as needed” is great for situations when a loop’s condition
must be checked not in the beginning or end of the loop, but in the middle or even in several places
of its body.
The continue directive is a “lighter version” of break. It doesn’t stop the whole loop. Instead, it stops
the current iteration and forces the loop to start a new one (if the condition allows).
We can use it if we’re done with the current iteration and would like to move on to the next one.
alert(i); // 1, then 3, 5, 7, 9
}
For even values of i, the continue directive stops executing the body and passes control to the next
iteration of for (with the next number). So the alert is only called for odd values.
if (i % 2) {
alert( i );
}
}
From a technical point of view, this is identical to the example above. Surely, we can just wrap the
code in an if block instead of using continue.
But as a side-effect, this created one more level of nesting (the alert call inside the curly braces). If
the code inside ofif is longer than a few lines, that may decrease the overall readability.
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 17 of 23
Please note that syntax constructs that are not expressions cannot be used with the ternary operator ?.
In particular, directives such as break/continue aren’t allowed there.
if (i > 5) {
alert(i);
} else {
continue;
}
…it stops working. Code like this will give a syntax error:
This is just another reason not to use the question mark operator ? instead of if.
For example, in the code below we loop over i and j, prompting for the coordinates (i, j) from (0,0) to
(3,3):
alert('Done!');
We need a way to stop the process if the user cancels the input.
The ordinary break after input would only break the inner loop. That’s not sufficient–labels, come to
the rescue!
The break <labelName> statement in the loop below breaks out to the label:
In the code above, break outer looks upwards for the label named outer and breaks out of that loop.
outer:
for (let i = 0; i < 3; i++) { ... }
The continue directive can also be used with a label. In this case, code execution jumps to the next
iteration of the labeled loop.
A call to break/continue is only possible from inside a loop and the label must be somewhere above
the directive.
Summary
To make an “infinite” loop, usually the while(true) construct is used. Such a loop, just like any other, can
be stopped with the break directive.
If we don’t want to do anything in the current iteration and would like to forward to the next one, we can
use the continue directive.
break/continue support labels before the loop. A label is the only way for break/continue to escape a
nested loop to go to an outer one.
Tasks
1. What is the last value alerted by this code? Why?
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 19 of 23
let i = 3;
while (i) {
alert( i-- );
}
For every loop iteration, write down which value it outputs and then compare it with the solution.
Both loops alert the same values, or not?
let i = 0;
while (++i < 5) alert( i );
let i = 0;
while (i++ < 5) alert( i );
For each loop write down which values it is going to show. Then compare with the answer.
5. Rewrite the code changing the for loop to while without altering its behavior (the output should stay
same).
6. Write a loop which prompts for a number greater than 100. If the visitor enters another number – ask
them to input again.
The loop must ask for a number until either the visitor enters a number greater than 100 or cancels
the input/enters an empty line.
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 20 of 23
Here we can assume that the visitor only inputs numbers. There’s no need to implement a special
handling for a non-numeric input in this task.
7. An integer number greater than 1 is called a prime if it cannot be divided without a remainder by
anything except 1 and itself.
In other words, n > 1 is a prime if it can’t be evenly divided by anything except 1 and n.
Write the code which outputs prime numbers in the interval from 2 to n.
For n = 10 the result will be 2,3,5,7.
P.S. The code should work for any n, not be hard-tuned for any fixed value.
The syntax
The switch has one or more case blocks and an optional default.
switch(x) {
case 'value1': // if (x === 'value1')
...
[break]
default:
...
[break]
}
The value of x is checked for a strict equality to the value from the first case (that is, value1)
then to the second (value2) and so on.
If the equality is found, switch starts to execute the code starting from the corresponding
case, until the nearest break (or until the end of switch).
If no case is matched then the default code is executed (if it exists).
An example
let a = 2 + 2;
switch (a) {
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 21 of 23
case 3:
alert( 'Too small' );
break;
case 4:
alert( 'Exactly!' );
break;
case 5:
alert( 'Too large' );
break;
default:
alert( "I don't know such values" );
}
Here the switch starts to compare a from the first case variant that is 3. The match fails.
Then 4. That’s a match, so the execution starts from case 4 until the nearest break.
If there is no break then the execution continues with the next case without any checks.
let a = 2 + 2;
switch (a) {
case 3:
alert( 'Too small' );
case 4:
alert( 'Exactly!' );
case 5:
alert( 'Too big' );
default:
alert( "I don't know such values" );
}
alert( 'Exactly!' );
alert( 'Too big' );
alert( "I don't know such values" );
For example:
let a = "1";
let b = 0;
switch (+a) {
case b + 1:
alert("this runs, because +a is 1, exactly equals b+1");
break;
Lesson 2 jyercia
JavaScript Fundamentals Part II Page 22 of 23
default:
alert("this doesn't run");
}
Here +a gives 1, that’s compared with b + 1 in case, and the corresponding code is executed.
Grouping of “case”
Several variants of case which share the same code can be grouped.
For example, if we want the same code to run for case 3 and case 5:
let a = 2 + 2;
switch (a) {
case 4:
alert('Right!');
break;
case 3: // (*) grouped two cases
case 5:
alert('Wrong!');
alert("Why don't you take a math class?");
break;
default:
alert('The result is strange. Really.');
}
The ability to “group” cases is a side-effect of how switch/case works without break. Here the
execution of case 3 starts from the line (*) and goes through case 5, because there’s no break.
Type matters
Let’s emphasize that the equality check is always strict. The values must be of the same type to
match.
break;
case 3:
alert( 'Never executes!' );
break;
default:
alert( 'An unknown value' );
}
Tasks
1. Write the code using if..else which would correspond to the following switch:
switch (browser) {
case 'Edge':
alert( "You've got the Edge!" );
break;
case 'Chrome':
case 'Firefox':
case 'Safari':
case 'Opera':
alert( 'Okay we support these browsers too' );
break;
default:
alert( 'We hope that this page looks ok!' );
}
if (a == 0) {
alert( 0 );
}
if (a == 1) {
alert( 1 );
}
if (a == 2 || a == 3) {
alert( '2,3' );
Lesson 2 jyercia