Fundamentals 3 Flashcards

1
Q

What are three logical operators in js?

A

&& and
|| or
! not

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the Nullish coalescing operator ‘??’?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What’s an example of using the the nullish coalescing operator?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you write a “while loop” in js?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How does a ‘do while’ loop work?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How does a “for” loop work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Can you omit any part of the “for” loop?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you break out of a loop?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the continue keyword?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

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

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!’).

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is a “switch statement” and how does it work?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Can you group cases together in a switch statement?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

In a switch statement, do the values need to be of the same type to match?

A

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.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are functions?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How do you declare a function?

A

To create a function we can use a function declaration.

It looks like this:

function showMessage() {
  alert( 'Hello everyone!' );
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you declare a function with parameters?

A

The function keyword goes first, then goes the name of the function, then a list of parameters between the parentheses (comma-separated, empty in the example above, we’ll see examples later) and finally the code of the function, also named “the function body”, between curly braces.

function name(parameter1, parameter2, ... parameterN) {
  ...body...
}
17
Q

How do you call on a function?

A
function showMessage() {
  alert( 'Hello everyone!' );
}

showMessage();
showMessage();
The call showMessage() executes the code of the function. Here we will see the message two times.

This example clearly demonstrates one of the main purposes of functions: to avoid code duplication.

If we ever need to change the message or the way it is shown, it’s enough to modify the code in one place: the function which outputs it.

18
Q

What is a local variable?

A

A variable declared inside a function is only visible inside that function.

For example:

function showMessage() {
  let message = "Hello, I'm JavaScript!"; // local variable

alert( message );
}

showMessage(); // Hello, I’m JavaScript!

alert( message ); //

19
Q

What is a Outer variable?

A

A function can access an outer variable as well, for example:

let userName = ‘John’;

function showMessage() {
  let message = 'Hello, ' + userName;
  alert(message);
}

showMessage(); // Hello, John

20
Q

Can a function modify a Outer variable? Will a local function of the same name overshadow an outer one?

A

The function has full access to the outer variable. It can modify it as well.

For instance:

let userName = ‘John’;

function showMessage() {
  userName = "Bob"; // (1) changed the outer variable
  let message = 'Hello, ' + userName;
  alert(message);
}

alert( userName ); // John before the function call

showMessage();

alert( userName ); // Bob, the value was modified by the function

The outer variable is only used if there’s no local one.

If a same-named variable is declared inside the function then it shadows the outer one.

21
Q

What a parameters and how can you use them?

A

We can pass arbitrary data to functions using parameters.

In the example below, the function has two parameters: from and text.

function showMessage(from, text) { // parameters: from, text
  alert(from + ': ' + text);
}

showMessage(‘Ann’, ‘Hello!’); // Ann: Hello! (*)
showMessage(‘Ann’, “What’s up?”); // Ann: What’s up? ()
When the function is called in lines (*) and (
), the given values are copied to local variables from and text. Then the function uses them.

22
Q

What is it called when a value is passed as a function parameter?

A

An argument.

In other words, to put these terms straight:

A parameter is the variable listed inside the parentheses in the function declaration (it’s a declaration time term).
An argument is the value that is passed to the function when it is called (it’s a call time term).
We declare functions listing their parameters, then call them passing arguments.

23
Q

How can you set up a default parameter? What happens then if the default parameter doesn’t have an argument passed?

A
function showMessage(from, text = "no text given") {
  alert( from + ": " + text );
}

showMessage(“Ann”); // Ann: no text given

this is also possible:

function showMessage(from, text = anotherFunction()) {
  // anotherFunction() only executed if no text given
  // its result becomes the value of text
}

In JavaScript, a default parameter is evaluated every time the function is called without the respective parameter.

In the example above, anotherFunction() isn’t called at all, if the text parameter is provided.

On the other hand, it’s independently called every time when text is missing.

24
Q

How do you return a value back into the calling code as the result?

A

The simplest example would be a function that sums two values:

function sum(a, b) {
  return a + b;
}
let result = sum(1, 2);
alert( result ); // 3
The directive return can be in any place of the function. When the execution reaches it, the function stops, and the value is returned to the calling code (assigned to result above).

There may be many occurrences of return in a single function. For instance:

function checkAge(age) {
  if (age >= 18) {
    return true;
  } else {
    return confirm('Do you have permission from your parents?');
  }
}

let age = prompt(‘How old are you?’, 18);

if ( checkAge(age) ) {
  alert( 'Access granted' );
} else {
  alert( 'Access denied' );
}
25
Q

Is it possible to use return without a value? What does a function technically return with an empty return or without it?

A

Yes.

That causes the function to exit immediately.

For example:

function showMovie(age) {
  if ( !checkAge(age) ) {
    return;
  }
  alert( "Showing you the movie" ); // (*)
  // ...
}
In the code above, if checkAge(age) returns false, then showMovie won’t proceed to the alert.

A function with an empty return or without it returns undefined

26
Q

How should you go about naming functions?

A

Functions are actions. So their name is usually a verb. It should be brief, as accurate as possible and describe what the function does, so that someone reading the code gets an indication of what the function does.

It is a widespread practice to start a function with a verbal prefix which vaguely describes the action. There must be an agreement within the team on the meaning of the prefixes.

For instance, functions that start with “show” usually show something.

Function starting with…

“get…” – return a value,
“calc…” – calculate something,
“create…” – create something,
“check…” – check something and return a boolean, etc.

showMessage(..) // shows a message
getAge(..) // returns the age (gets it somehow)
calcSum(..) // calculates a sum and returns the result
createForm(..) // creates a form (and usually returns it)
checkPermission(..) // checks a permission, returns true/false

27
Q

Should the code within functions be as short as possible? What should you do if something you’re working with is big?

A

Yes.

Functions should be short and do exactly one thing. If that thing is big, maybe it’s worth it to split the function into a few smaller functions. Sometimes following this rule may not be that easy, but it’s definitely a good thing.

28
Q

What would the syntax be for a function called name that has four parameters?

A
function name(parameters, delimited, by, comma) {
  /* code */
}
29
Q

What is a Function Expression? Do you need to name Function Expressions? Do Function Expressions use a semi colon at the end?

A

It allows us to create a new function in the middle of any expression.

For example:

let sayHi = function() {
  alert( "Hello" );
};
Here we can see a variable sayHi getting a value, the new function, created as function() { alert("Hello"); }.

As the function creation happens in the context of the assignment expression (to the right side of =), this is a Function Expression.

Please note, there’s no name after the function keyword. Omitting a name is allowed for Function Expressions.

30
Q

In Javascript, is a function technically a value? How does it differ from other languages?

A
function sayHi() {
  alert( "Hello" );
}

alert( sayHi ); // shows the function code
Please note that the last line does not run the function, because there are no parentheses after sayHi. There are programming languages where any mention of a function name causes its execution, but JavaScript is not like that.

In JavaScript, a function is a value, so we can deal with it as a value. The code above shows its string representation, which is the source code.

Surely, a function is a special value, in the sense that we can call it like sayHi().

But it’s still a value. So we can work with it like with other kinds of values.

31
Q

What are the functions showOk() and showCancel() of ask() called below?

function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}
function showOk() {
  alert( "You agreed." );
}
function showCancel() {
  alert( "You canceled the execution." );
}
// usage: functions showOk, showCancel are passed as arguments to ask
ask("Do you agree?", showOk, showCancel);
A

The arguments showOk and showCancel of ask are called callback functions or just callbacks.

The idea is that we pass a function and expect it to be “called back” later if necessary. In our case, showOk becomes the callback for “yes” answer, and showCancel for “no” answer.

32
Q

What is the difference between a your normal Function Declaration and a Function Expression? Which one is more commonly preferred?

A

Function Declarations are processed before the code block is executed. They are visible everywhere in the block.

Function Expressions are created when the execution flow reaches them.

In most cases when we need to declare a function, a Function Declaration is preferable, because it is visible prior to the declaration itself. That gives us more flexibility in code organization, and is usually more readable.

33
Q

What are Arrow Function, how do they work?

A

There’s another very simple and concise syntax for creating functions, that’s often better than Function Expressions.

It’s called “arrow functions”, because it looks like this:

let func = (arg1, arg2, ..., argN) => expression;
This creates a function func that accepts arguments arg1..argN, then evaluates the expression on the right side with their use and returns its result.

In other words, it’s the shorter version of:

let func = function(arg1, arg2, ..., argN) {
  return expression;
};
34
Q

What is this Arrow Function the same as if it were a Function Expression?

let sum = (a, b) => a + b;

alert( sum(1, 2) ); // 3

A
let sum = function(a, b) {
  return a + b;
};