Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
108 views

Conditional Operators: If, '?'

The document discusses JavaScript conditional statements and operators including if, else if, else, and the conditional/ternary operator (?). The if statement evaluates a condition and executes a code block if the condition is true. else if allows testing multiple conditions. The conditional operator (? ) assigns a value based on whether a condition is true or false. Multiple ? can chain conditions to return different values.

Uploaded by

Jaja Arcenal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
108 views

Conditional Operators: If, '?'

The document discusses JavaScript conditional statements and operators including if, else if, else, and the conditional/ternary operator (?). The if statement evaluates a condition and executes a code block if the condition is true. else if allows testing multiple conditions. The conditional operator (? ) assigns a value based on whether a condition is true or false. Multiple ? can chain conditions to return different values.

Uploaded by

Jaja Arcenal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 23

JavaScript Fundamentals Part II Page 1 of 23

Conditional operators: if, '?'

Sometimes, we need to perform different actions based on different conditions.

To do that, we can use the if statement and the conditional operator ?, that’s also called a “question
mark” operator.

The “if” statement

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”.

So, the code under this condition would never execute:

if (false) { // 0 is falsy
...
}

…and inside this condition – it always will:

if (true) { // 1 is truthy
...
}

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 2 of 23

We can also pass a pre-evaluated boolean value to if, like this:

let cond = (year == 2015); // equality evaluates to true or false

if (cond) {
...
}

The “else” clause

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
}

Several conditions: “else if”

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?', '');

if (year < 2015) {


alert( 'Too early...' );
} else if (year > 2015) {
alert( 'Too late' );
} else {
alert( 'Exactly!' );
}

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.

There can be more else if blocks. The final else is optional.

Conditional operator ‘?’

Sometimes, we need to assign a variable depending on a condition.

For instance:

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 3 of 23

let accessAllowed;
let age = prompt('How old are you?', '');

if (age > 18) {


accessAllowed = true;
} else {
accessAllowed = false;
}

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 syntax is:

let result = condition ? value1 : value2;

The condition is evaluated: if it’s truthy then value1 is returned, otherwise – value2.

For example:

let accessAllowed = (age > 18) ? true : false;

Technically, we can omit the parentheses around age > 18. The question mark operator has a low
precedence, so it executes after the comparison >.

This example will do the same thing as the previous one:

// the comparison operator "age > 18" executes first anyway


// (no need to wrap it into parentheses)
let accessAllowed = age > 18 ? true : false;

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:

let age = prompt('age?', 18);

let message = (age < 3) ? 'Hi, baby!' :


(age < 18) ? 'Hello!' :
(age < 100) ? 'Greetings!' :
'What an unusual age!';

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:

1. The first question mark checks whether age < 3.


2. If true – it returns 'Hi, baby!'. Otherwise, it continues to the expression after the colon ‘":"’,
checking age < 18.
3. If that’s true – it returns 'Hello!'. Otherwise, it continues to the expression after the next colon
‘":"’, checking age < 100.
4. If that’s true – it returns 'Greetings!'. Otherwise, it continues to the expression after the last
colon ‘":"’, returning 'What an unusual age!'.

Here’s how this looks using if..else:

if (age < 3) {
message = 'Hi, baby!';
} else if (age < 18) {
message = 'Hello!';
} else if (age < 100) {
message = 'Greetings!';
} else {
message = 'What an unusual age!';
}

Non-traditional use of ‘?’

Sometimes the question mark ? is used as a replacement for if:

let company = prompt('Which company created JavaScript?', '');


(company == 'Netscape') ? alert('Right!') : alert('Wrong.');

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:

 1, if the value is greater than zero,


 -1, if less than zero,
 0, if equals zero.

In this task we assume that the input is always a number.

4. Rewrite this if using the ternary operator '?':

if (a + b < 4) {
result = 'Below';
} else {
result = 'Over';
}

5. Rewrite if..else using multiple ternary operators '?'.

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)

The “OR” operator is represented with two vertical line symbols:

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.

There are four possible logical combinations:

alert( true || true ); // true


alert( false || true ); // true
alert( true || false ); // true
alert( false || false ); // false

As we can see, the result is always true except for the case when both operands are false.

If an operand is not a boolean, it’s converted to a boolean for the evaluation.

For instance, the number 1 is treated as true, the number 0 as false:

if (1 || 0) { // works just like if( true || false )


alert( 'truthy!' );
}

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;

if (hour < 10 || hour > 18) {


alert( 'The office is closed.' );
Lesson 2  jyercia
JavaScript Fundamentals Part II Page 7 of 23

}
We can pass more conditions:
let hour = 12;
let isWeekend = true;

if (hour < 10 || hour > 18 || isWeekend) {


alert( 'The office is closed.' ); // it is the weekend
}

OR finds the first truthy value

The logic described above is somewhat classical. Now, let’s bring in the “extra” features of
JavaScript.

The extended algorithm works as follows.

Given multiple OR’ed values:

result = value1 || value2 || value3;

The OR || operator does the following:

 Evaluates operands from left to right.


 For each operand, converts it to boolean. If the result is true, stops and returns the original
value of that operand.
 If all operands have been evaluated (i.e. all were false), returns the last operand.

A value is returned in its original form, without the conversion.

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)

alert( null || 1 ); // 1 (1 is the first truthy value)


alert( null || 0 || 1 ); // 1 (the first truthy value)
alert( undefined || null || 0 ); // 0 (all falsy, returns the last value)

This leads to some interesting usage compared to a “pure, classical, boolean-only OR”.

1. Getting the first truthy value from a list of variables or expressions.

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?

We can use OR ||:

let currentUser = null;


let defaultUser = "John";

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 8 of 23

let name = currentUser || defaultUser || "unnamed";

alert( name ); // selects "John" – the first truthy value

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.

In the example below, x does not get assigned:

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)

The AND operator is represented with two ampersands &&:

result = a && b;

In classical programming, AND returns true if both operands are truthy and false otherwise:

alert( true && true ); // true


alert( false && true ); // false
alert( true && false ); // false
alert( false && false ); // false

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 9 of 23

An example with if:

let hour = 12;


let minute = 30;

if (hour == 12 && minute == 30) {


alert( 'The time is 12:30' );
}

Just as with OR, any value is allowed as an operand of AND:

if (1 && 0) { // evaluated as true && false


alert( "won't work, because the result is falsy" );
}

AND finds the first falsy value

Given multiple AND’ed values:

result = value1 && value2 && value3;

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.

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:

// if the first operand is truthy,


// AND returns the second operand:
alert( 1 && 0 ); // 0
alert( 1 && 5 ); // 5

// if the first operand is falsy,


// AND returns it. The second operand is ignored
alert( null && 5 ); // null
alert( 0 && "no matter what" ); // 0

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

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 10 of 23

Precedence of AND && is higher than OR ||

The precedence of AND && operator is higher than OR ||.

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.

So we basically have an analogue for:

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)

The boolean NOT operator is represented with an exclamation sign !.

The syntax is pretty simple:

result = !value;

The operator accepts a single argument and does the following:

1. Converts the operand to boolean type: true/false.


2. Returns the inverse value.

For instance:

alert( !true ); // false


alert( !0 ); // true

A double NOT !! is sometimes used for converting a value to boolean type:

alert( !!"non-empty string" ); // true


alert( !!null ); // false
Lesson 2  jyercia
JavaScript Fundamentals Part II Page 11 of 23

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:

alert( Boolean("non-empty string") ); // true


alert( Boolean(null) ); // false

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 );

2. What will the code below output?


alert( alert(1) || 2 || alert(3) );

3. What is this code going to show?


alert( 1 && null && 2 );

4. What will this code show?


alert( alert(1) && alert(2) );

5. What will the result be?


alert( null || 2 && 3 || 4 );
6. Write an “if” condition to check that age is between 14 and 90 inclusively.
“Inclusively” means that age can reach the edges 14 or 90.

7. Write an if condition to check that age is NOT between 14 and 90 inclusively.


Create two variants: the first one using NOT !, the second one – without it.

8. Which of these alerts are going to execute?


What will the results of the expressions be inside if(...)?

if (-1 || 0) alert( 'first' );


if (-1 && 0) alert( 'second' );
if (null || -1 && 1) alert( 'third' );

9. Write the code which asks for a login with prompt.


If the visitor enters "Admin", then prompt for a password, if the input is an empty line or Esc – show
“Canceled.”, if it’s another string – then show “I don’t know you”.
The password is checked as follows:
 If it equals “TheMaster”, then show “Welcome!”,
 Another string – show “Wrong password”,
 For an empty string or cancelled input, show “Canceled.”

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.

Loops: while and for

We often need to repeat actions.

For example, outputting goods from a list one after another or just running the same code for each
number from 1 to 10.

Loops are a way to repeat the same code multiple times.

The “while” loop

The while loop has the following syntax:

while (condition) {
// code
// so-called "loop body"
}

While the condition is true, the code from the loop body is executed.

For instance, the loop below outputs i while i < 3:

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.

For instance, a shorter way to write while (i != 0) is while (i):

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 “do…while” loop

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(…) {…}.

The “for” loop

The for loop is the most commonly used loop.

It looks like this:

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 14 of 23

for (begin; condition; step) {


// ... loop body ...
}

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:

for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2


alert(i);
}

Let’s examine the for statement part-by-part:

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.

Here’s exactly what happens in our case:

// for (let i = 0; i < 3; i++) alert(i)

// 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

Inline variable declaration

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.

for (let i = 0; i < 3; i++) {


alert(i); // 0, 1, 2
}
alert(i); // error, no such variable

Instead of defining a variable, we could use an existing one:

let i = 0;

Lesson 2  jyercia
JavaScript Fundamentals Part II Page 15 of 23

for (i = 0; i < 3; i++) { // use an existing variable


alert(i); // 0, 1, 2
}

alert(i); // 3, visible, because declared outside of the loop

Skipping parts

Any part of for can be skipped.

For example, we can omit begin if we don’t need to do anything at the loop start.

Like here:

let i = 0; // we have i already declared and assigned

for (; i < 3; i++) { // no need for "begin"


alert( i ); // 0, 1, 2
}

We can also remove the step part:

let i = 0;

for (; i < 3;) {


alert( i++ );
}

This makes the loop identical to while (i < 3).

We can actually remove everything, creating an infinite loop:

for (;;) {
// repeats without limits
}

Please note that the two for semicolons ; must be present. Otherwise, there would be a syntax error.

Breaking the loop

Normally, a loop exits when its condition becomes falsy.

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

if (!value) break; // (*)


sum += value;
}
alert( 'Sum: ' + sum );

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.

Continue to the next iteration

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.

The loop below uses continue to output only odd values:

for (let i = 0; i < 10; i++) {

// if true, skip the remaining part of the body


if (i % 2 == 0) continue;

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.

The continue directive helps decrease nesting

A loop that shows odd values could look like this:

for (let i = 0; i < 10; i++) {

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.

No break/continue to the right side of ‘?’

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.

For example, if we take this code:

if (i > 5) {
alert(i);
} else {
continue;
}

…and rewrite it using a question mark:

(i > 5) ? alert(i) : continue; // continue isn't allowed here

…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.

Labels for break/continue

Sometimes we need to break out from multiple nested loops at once.

For example, in the code below we loop over i and j, prompting for the coordinates (i, j) from (0,0) to
(3,3):

for (let i = 0; i < 3; i++) {


for (let j = 0; j < 3; j++) {
let input = prompt(`Value at coords (${i},${j})`, '');
// what if I want to exit from here to Done (below)?
}
}

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!

A label is an identifier with a colon before a loop:

labelName: for (...) {


...
}

The break <labelName> statement in the loop below breaks out to the label:

outer: for (let i = 0; i < 3; i++) {


for (let j = 0; j < 3; j++) {
let input = prompt(`Value at coords (${i},${j})`, '');
// if an empty string or canceled, then break out of both loops
if (!input) break outer; // (*)
Lesson 2  jyercia
JavaScript Fundamentals Part II Page 18 of 23

// do something with the value...


}
}
alert('Done!');

In the code above, break outer looks upwards for the label named outer and breaks out of that loop.

So the control goes straight from (*) to alert('Done!').

We can also move the label onto a separate line:

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.

Labels are not a “goto”

Labels do not allow us to jump into an arbitrary place in the code.

For example, it is impossible to do this:

break label; // jumps to label? No.

label: for (...)

A call to break/continue is only possible from inside a loop and the label must be somewhere above
the directive.

Summary

We covered 3 types of loops:

 while – The condition is checked before each iteration.


 do..while – The condition is checked after each iteration.
 for (;;) – The condition is checked before each iteration, additional settings available.

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-- );
}

2. Which values does the while loop show?

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?

1. The prefix form ++i:

let i = 0;
while (++i < 5) alert( i );

2. The postfix form i++

let i = 0;
while (i++ < 5) alert( i );

3. Which values get shown by the "for" loop?

For each loop write down which values it is going to show. Then compare with the answer.

Both loops alert same values or not?

1. The postfix form:

for (let i = 0; i < 5; i++) alert( i );

2. The prefix form:

for (let i = 0; i < 5; ++i) alert( i );

4. Use the for loop to output even numbers from 2 to 10.

5. Rewrite the code changing the for loop to while without altering its behavior (the output should stay
same).

for (let i = 0; i < 3; i++) {


alert( `number ${i}!` );
}

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.

For example, 5 is a prime, because it cannot be divided without a remainder by 2, 3 and 4.

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 "switch" statement

 A switch statement can replace multiple if checks.

 It gives a more descriptive way to compare a value with multiple variants.

The syntax

The switch has one or more case blocks and an optional default.

It looks like this:

switch(x) {
case 'value1': // if (x === 'value1')
...
[break]

case 'value2': // if (x === 'value2')


...
[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

An example of switch (the executed code is highlighted):

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.

An example without break:

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" );
}

In the example above we’ll see sequential execution of three alerts:

alert( 'Exactly!' );
alert( 'Too big' );
alert( "I don't know such values" );

Any expression can be a switch/case argument

Both switch and case allow arbitrary expressions.

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.');
}

Now both 3 and 5 show the same message.

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.

For example, let’s consider the code:

let arg = prompt("Enter a value?");


switch (arg) {
case '0':
case '1':
alert( 'One or zero' );
break;
case '2':
alert( 'Two' );
Lesson 2  jyercia
JavaScript Fundamentals Part II Page 23 of 23

break;
case 3:
alert( 'Never executes!' );
break;
default:
alert( 'An unknown value' );
}

1. For 0, 1, the first alert runs.


2. For 2 the second alert runs.
3. But for 3, the result of the prompt is a string "3", which is not strictly equal === to the
number 3. So we’ve got a dead code in case 3! The default variant will execute.

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!' );
}

2. Rewrite the code below using a single switch statement:

let a = +prompt('a?', '');

if (a == 0) {
alert( 0 );
}
if (a == 1) {
alert( 1 );
}

if (a == 2 || a == 3) {
alert( '2,3' );

Lesson 2  jyercia

You might also like