Fundamentals 3 Flashcards
What are three logical operators in js?
&& and
|| or
! not
What is the Nullish coalescing operator ‘??’?
The nullish coalescing operator is written as two question marks ??.
As it treats null and undefined similarly, we’ll use a special term here, in this article. For brevity, we’ll say that a value is “defined” when it’s neither null nor undefined.
The result of a ?? b is:
if a is defined, then a,
if a isn’t defined, then b.
In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one.
The nullish coalescing operator isn’t anything completely new. It’s just a nice syntax to get the first “defined” value of the two.
What’s an example of using the the nullish coalescing operator?
For example, here we show user if its value isn’t null/undefined, otherwise Anonymous:
let user;
alert(user ?? “Anonymous”); // Anonymous (user not defined)
How do you write a “while loop” in js?
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 truthy, 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 );
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
How does a ‘do while’ loop work?
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.
How does a “for” loop work?
A “for” loop is the most commonly used loop.
for (let i = 0; i < 3; i++) { // shows 0, then 1, then 2 alert(i); }
for (begin; condition; step) { // ... loop body ... }
That is, begin executes once, and then it iterates: after each condition test, body and step are executed.
Can you omit any part of the “for” loop?
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
}
How do you break out of a 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”, ‘’);
if (!value) break; // (*)
sum += value;
}
alert( ‘Sum: ‘ + sum );
What is the continue keyword?
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.
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 (2,2):
for (let i = 0; i < 3; i++) {
for (let j = 0; j < 3; j++) {
let input = prompt(`Value at coords (${i},${j})`, '');
// what if we 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 - so what can come to the rescue?
A label is an identifier with a colon before a loop:
labelName: for (…) {
…
}
The break 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; // (*)
// 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!’).
What is a “switch statement” and how does it work?
A switch statement can replace multiple if checks. It gives a more descriptive way to compare a value with multiple variants.
The switch has one or more case blocks and an optional default.
The following switch statement will alert with ‘Exactly!’.
let a = 2 + 2;
switch (a) { case 3: alert( 'Too small' ); break; case 4: alert( 'Exactly!' ); break; case 5: alert( 'Too big' ); 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.
Can you group cases together in a switch statement?
Yes.
For example, if we want the same code to run for case 3 and case 5:
let a = 3;
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.
In a switch statement, do the values need to be of the same type to match?
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’ );
break;
case 3: alert( 'Never executes!' ); break; default: alert( 'An unknown value' ); } For 0, 1, the first alert runs. For 2 the second alert runs. 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.
What are functions?
Quite often we need to perform a similar action in many places of the script.
For example, we need to show a nice-looking message when a visitor logs in, logs out and maybe somewhere else.
Functions are the main “building blocks” of the program. They allow the code to be called many times without repetition.
We’ve already seen examples of built-in functions, like alert(message), prompt(message, default) and confirm(question). But we can create functions of our own as well.
How do you declare a function?
To create a function we can use a function declaration.
It looks like this:
function showMessage() { alert( 'Hello everyone!' ); }