JS fundamentals Flashcards

1
Q

What is alert function ?

A

It shows a message and waits for the user to press “OK”.

For example:

alert(“Hello”);
The mini-window with the message is called a modal window. The word “modal” means that the visitor can’t interact with the rest of the page, press other buttons, etc, until they have dealt with the window. In this case – until they press “OK”.

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

What is prompt function ?

A

The function prompt accepts two arguments:

result = prompt(title, [default]);
It shows a modal window with a text message, an input field for the visitor, and the buttons OK/Cancel.

title -The text to show the visitor.
default - An optional second parameter, the initial value for the input field.
The square brackets in syntax […] -The square brackets around default in the syntax above denote that the parameter is optional, not required.

The visitor can type something in the prompt input field and press OK. Then we get that text in the result. Or they can cancel the input by pressing Cancel or hitting the Esc key, then we get null as the result.

The call to prompt returns the text from the input field or null if the input was canceled.

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

What is confirm function ?

A

The syntax:

result = confirm(question);
The function confirm shows a modal window with a question and two buttons: OK and Cancel.

The result is true if OK is pressed and false otherwise.

For example:

let isBoss = confirm(“Are you the boss?”);

alert( isBoss ); // true if OK is pressed

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

How string conversion happens ?

A

String conversion happens when we need the string form of a value.

For example, alert(value) does it to show the value.

We can also call the String(value) function to convert a value to a string:

let value = true;
alert(typeof value); // boolean

value = String(value); // now value is a string “true”
alert(typeof value); // string
String conversion is mostly obvious. A false becomes “false”, null becomes “null”, etc.

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

Numeric conversion
alert( “6” / “2” );
Output ?

A

3 , because it is automatically converted

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

How to explicitly convert to number ?

A

We can use the Number(value) function to explicitly convert a value to a number:

let str = "123";
alert(typeof str); // string

let num = Number(str); // becomes a number 123

alert(typeof num); // number
Explicit conversion is usually required when we read a value from a string-based source like a text form but expect a number to be entered.

If the string is not a valid number, the result of such a conversion is NaN. For instance:

let age = Number(“an arbitrary string instead of a number”);

alert(age); // NaN, conversion failed

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

alert( Number(“ 123 “) );

A

123 without whitespaces

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

alert( Number(“123z”) );

A

NaN (error reading a number at “z”)

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

alert( Number(true) );

A

1

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

alert( Number(false) );

A

0

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

alert( Boolean(1) );

A

true

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

alert( Boolean(0) );

A

false

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

alert( Boolean(“hello”) );

A

true

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

alert( Boolean(“”) );

A

false

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

alert( Boolean(“0”) );

A

true

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

alert( Boolean(“ “) );

A

// spaces, also true (any non-empty string is true)

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

What is an operand ?

A

An operand – is what operators are applied to. For instance, in the multiplication of 5 * 2 there are two operands: the left operand is 5 and the right operand is 2. Sometimes, people call these “arguments” instead of “operands”.

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

What is an operator ?

A

An operator is unary if it has a single operand. For example, the unary negation - reverses the sign of a number:

let x = 1;

x = -x;
alert( x ); // -1, unary negation was applied
An operator is binary if it has two operands. The same minus exists in binary form as well:

let x = 1, y = 3;
alert( y - x ); // 2, binary minus subtracts values
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

alert( ‘1’ + 2 );

alert( 2 + ‘1’ );

A
// "12"
// "21"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

alert( +true );

alert( +”” );

A
// 1
0
It actually does the same thing as Number(...), but is shorter.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q
let counter = 1;
let a = ++counter; 

alert(a);

A

// 2

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q
let counter = 1;
let a = counter++; 

alert(a);

A

// 1

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q
let result = 5 > 4;
alert( result );
A
let result = 5 > 4; // assign the result of the comparison
alert( result ); // true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

alert( ‘Z’ > ‘A’ );
alert( ‘Glow’ > ‘Glee’ );
alert( ‘Bee’ > ‘Be’ );

A

alert( ‘Z’ > ‘A’ ); // true
alert( ‘Glow’ > ‘Glee’ ); // true
alert( ‘Bee’ > ‘Be’ ); // true

To see whether a string is greater than another, JavaScript uses the so-called “dictionary” or “lexicographical” order.

In other words, strings are compared letter-by-letter.

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

“A” == “a” Are these equal ?

A

case matters. A capital letter “A” is not equal to the lowercase “a”. Which one is greater? The lowercase “a”. Why? Because the lowercase character has a greater index in the internal encoding table JavaScript uses (Unicode). We’ll get back to specific details and consequences of this in the chapter Strings.

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

alert( ‘2’ > 1 );

alert( ‘01’ == 1 );

A

alert( ‘2’ > 1 ); // true, string ‘2’ becomes a number 2
alert( ‘01’ == 1 ); // true, string ‘01’ becomes a number 1
When comparing values of different types, JavaScript converts the values to numbers.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q
let a = 0;
alert( Boolean(a) ); 
let b = "0";
alert( Boolean(b) ); 

alert(a == b);

A
let a = 0;
alert( Boolean(a) ); // false
let b = "0";
alert( Boolean(b) ); // true

alert(a == b); // true!

It is possible that at the same time:
1-Two values are equal.
2-One of them is true as a boolean and the other one is false as a boolean.

From JavaScript’s standpoint, this result is quite normal. An equality check converts values using the numeric conversion (hence “0” becomes 0), while the explicit Boolean conversion uses another set of rules.

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

alert( 0 == false );

alert( ‘’ == false );

A

alert( 0 == false ); // true
alert( ‘’ == false ); // true

A regular equality check == has a problem. It cannot differentiate 0 from false:

This happens because operands of different types are converted to numbers by the equality operator ==. An empty string, just like false, becomes a zero.

What to do if we’d like to differentiate 0 from false?

A strict equality operator === checks the equality without type conversion.

In other words, if a and b are of different types, then a === b immediately returns false without an attempt to convert them.

Let’s try it:

alert( 0 === false ); // false, because the types are different
There is also a “strict non-equality” operator !== analogous to !=.

The strict equality operator is a bit longer to write, but makes it obvious what’s going on and leaves less room for errors.

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

alert( null === undefined );

A

alert( null === undefined ); // false

These values are different, because each of them is a different type.

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

alert( null == undefined );

A

alert( null == undefined ); // true
There’s a special rule. These two are a “sweet couple”: they equal each other (in the sense of ==), but not any other value.

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

alert( null > 0 );
alert( null == 0 );
alert( null >= 0 );

A

alert( null > 0 ); // (1) false
alert( null == 0 ); // (2) false
alert( null >= 0 ); // (3) true

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

alert( undefined > 0 );
alert( undefined < 0 );
alert( undefined == 0 );

A

alert( undefined > 0 ); // false (1)
alert( undefined < 0 ); // false (2)
alert( undefined == 0 ); // false (3)

Why does it dislike zero so much? Always false!

We get these results because:

Comparisons (1) and (2) return false because undefined gets converted to NaN and NaN is a special numeric value which returns false for all comparisons.
The equality check (3) returns false because undefined only equals null, undefined, and no other value.

33
Q

let age = prompt(‘age?’, 18);

let message = (age < 3) ? ‘Hi, baby!’ :
(age < 18) ? ‘Hello!’ :
(age < 100) ? ‘Greetings!’ :
‘What an unusual age!’;

alert( message );

Would this work, if yes then explain.

A

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:

The first question mark checks whether age < 3.
If true – it returns ‘Hi, baby!’. Otherwise, it continues to the expression after the colon ‘”:”’, checking age < 18.
If that’s true – it returns ‘Hello!’. Otherwise, it continues to the expression after the next colon ‘”:”’, checking age < 100.
If that’s true – it returns ‘Greetings!’. Otherwise, it continues to the expression after the last colon ‘”:”’, returning ‘What an unusual age!’.

34
Q

alert( 1 || 0 );

alert( null || 1 );
alert( null || 0 || 1 );

alert( undefined || null || 0 );

A

alert( 1 || 0 ); // 1 (1 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)

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.

35
Q

let firstName = “”;
let lastName = “”;
let nickName = “SuperCoder”;

alert( firstName || lastName || nickName || “Anonymous”);

A

let firstName = “”;
let lastName = “”;
let nickName = “SuperCoder”;

alert( firstName || lastName || nickName || “Anonymous”); // SuperCoder

36
Q

true || alert(“printed”);
false || alert(“printed”);
Short circuiting in OR

A

only the second message is printed:
Another feature of OR || operator is the so-called “short-circuit” evaluation.
It means that || processes its arguments until the first truthy value is reached, and then the value is returned immediately, without even touching the other argument.
The importance of this feature becomes obvious if an operand isn’t just a value, but an expression with a side effect, such as a variable assignment or a function call.

In the first line, the OR || operator stops the evaluation immediately upon seeing true, so the alert isn’t run.
Sometimes, people use this feature to execute commands only if the condition on the left part is falsy.

37
Q

alert( 1 && 0 );

alert( 1 && 5 );

A

// if the first operand is truthy,
// AND returns the second operand:
alert( 1 && 0 ); // 0
alert( 1 && 5 ); // 5

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.

38
Q

alert( null && 5 );

alert( 0 && “no matter what” );

A

// if the first operand is falsy,
// AND returns it. The second operand is ignored
alert( null && 5 ); // null
alert( 0 && “no matter what” ); // 0

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.

39
Q

alert( 1 && 2 && null && 3 );

A

alert( 1 && 2 && null && 3 ); // null

We can also pass several values in a row. See how the first falsy one is returned:

40
Q

Between && and || which has higher precedence ?

A

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

41
Q

How NOT operator works ?

A

The operator accepts a single argument and does the following:

Converts the operand to boolean type: true/false.
Returns the inverse value.
For instance:

alert( !true ); // false
alert( !0 ); // true

42
Q

alert( !!”non-empty string” );

alert( !!null );

A

alert( !!”non-empty string” ); // true
alert( !!null ); // false

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.

43
Q

What is 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. We’ll say that an expression 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.

44
Q

Give a use case for ?? with an example

A

The common use case for ?? is to provide a default value for a potentially undefined variable.

For example, here we show user if defined, otherwise Anonymous:

let user;

alert(user ?? “Anonymous”); // Anonymous (user not defined)
Here’s the example with user assigned to a name:

let user = “John”;

alert(user ?? “Anonymous”); // John (user defined)
We can also use a sequence of ?? to select the first value from a list that isn’t null/undefined.

45
Q

Since || and ?? does almost the same thing, then What is the difference between them ?

A

The important difference between them is that:

|| returns the first truthy value.
?? returns the first defined value.
In other words, || doesn’t distinguish between false, 0, an empty string “” and null/undefined. They are all the same – falsy values. If any of these is the first argument of ||, then we’ll get the second argument as the result.

In practice though, we may want to use default value only when the variable is null/undefined. That is, when the value is really unknown/not set.

For example, consider this:

let height = 0;

alert(height || 100); // 100
alert(height ?? 100); // 0
The height || 100 checks height for being a falsy value, and it’s 0, falsy indeed.
so the result of || is the second argument, 100.

The height ?? 100 checks height for being null/undefined, and it’s not,
so the result is height “as is”, that is 0.

In practice, the zero height is often a valid value, that shouldn’t be replaced with the default. So ?? does just the right thing.

46
Q

Which has higher presedence - || or ??

A

The precedence of the ?? operator is the same as ||. They both equal 4 in the MDN table.

47
Q

let x = 1 && 2 ?? 3;

A
let x = 1 && 2 ?? 3; // Syntax error
Due to safety reasons, JavaScript forbids using ?? together with && and || operators, unless the precedence is explicitly specified with parentheses.

Use explicit parentheses to work around it:

let x = (1 && 2) ?? 3; // Works

alert(x); // 2

48
Q

What is do..while loop and when we use it ?

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. Usually, the other form is preferred: while(…) {…}.

49
Q

how to make an infinite loop in a for loop ?

A
for (;;) {
  // repeats without limits
}
50
Q

Can we use break/continue statements with the ternary operator ?

A

No

51
Q

How labels for break/continue work ?

A

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

52
Q

In switch statement, which type of equality is checked ?

A

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

53
Q

What happens if there is no break statement in the switch case ?

A

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

54
Q
let a = "1";
let b = 0;

switch (+a) {
case b + 1:
alert(“A runs “);
break;

default:
alert(“B runs”);
}

A

A runs

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;

default:
alert(“this doesn’t run”);
}
Here +a gives 1, that’s compared with b + 1 in case, and the corresponding code is executed.

55
Q

Can we group cases in a switch statement ?

A

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

56
Q
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( 'Three' );
    break;
  default:
    alert( 'An unknown value' );
A
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.

57
Q

is it a good practice to have low to none global variables ?

A

Variables declared outside of any function, such as the outer userName in the code above, are called global.

Global variables are visible from any function (unless shadowed by locals).

It’s a good practice to minimize the use of global variables. Modern code has few or no globals. Most variables reside in their functions. Sometimes though, they can be useful to store project-level data.

58
Q

What is a parameter ?

A

A parameter is the variable listed inside the parentheses in the function declaration (it’s a declaration time term)

59
Q

What is an argument ?

A

An argument is the value that is passed to the function when it is called (it’s a call time term).

60
Q

Does javascript throws an error if an argument is not passed to a function ?

A

If a function is called, but an argument is not provided, then the corresponding value becomes undefined.

For instance, the aforementioned function showMessage(from, text) can be called with a single argument:

showMessage(“Ann”);
That’s not an error. Such a call would output “Ann: undefined”. As the value for text isn’t passed, it becomes undefined.

We can specify the so-called “default” (to use if omitted) value for a parameter in the function declaration, using =

61
Q

How default values are given to the function ?

A

We can specify the so-called “default” (to use if omitted) value for a parameter in the function declaration, using =:

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

showMessage(“Ann”); // Ann: no text given
Now if the text parameter is not passed, it will get the value “no text given”

Here “no text given” is a string, but it can be a more complex expression, which is only evaluated and assigned if the parameter is missing. So, this is also possible:

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

Can we pass another function as a default value in any function in JS ?

A
YES
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.

63
Q

A function with empty return or without it returns _____?

A

A function with an empty return or without it returns undefined
If a function does not return a value, it is the same as if it returns undefined:

function doNothing() { /* empty */ }

alert( doNothing() === undefined ); // true
An empty return is also the same as return undefined:

function doNothing() {
  return;
}

alert( doNothing() === undefined ); // true

64
Q

What is the practice of One function- One action ?

A

A function should do exactly what is suggested by its name, no more.

Two independent actions usually deserve two functions, even if they are usually called together (in that case we can make a 3rd function that calls those two).

A few examples of breaking this rule:

getAge – would be bad if it shows an alert with the age (should only get).
createForm – would be bad if it modifies the document, adding a form to it (should only create it and return).
checkPermission – would be bad if it displays the access granted/denied message (should only perform the check and return the result).
These examples assume common meanings of prefixes. You and your team are free to agree on other meanings, but usually they’re not much different. In any case, you should have a firm understanding of what a prefix means, what a prefixed function can and cannot do. All same-prefixed functions should obey the rules. And the team should share the knowledge.

65
Q

Values passed to a function as parameters are copied to its local variables before using it in the function. is it True or False ?

A

True

66
Q

What is an function expression ?

A

There is another syntax for creating a function that is called a Function Expression.

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.

67
Q

Can we omit a function name in function expressions ?

A

Yes

68
Q
Why is there a semicolon at the end of an function expression?
function sayHi() {
  // ...
}
let sayHi = function() {
  // ...
};
A
Since a function is a value, therefore, 
The semicolon would be there for a simpler assignment, such as let sayHi = 5;, and it’s also there for a function assignment.
69
Q

What are callback functions, explain with an example ?

A

Let’s look at more examples of passing functions as values and using function expressions.

We’ll write a function ask(question, yes, no) with three parameters:

question
Text of the question
yes
Function to run if the answer is “Yes”
no
Function to run if the answer is “No”
The function should ask the question and, depending on the user’s answer, call yes() or no():
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);
In practice, such functions are quite useful. The major difference between a real-life ask and the example above is that real-life functions use more complex ways to interact with the user than a simple confirm. In the browser, such function usually draws a nice-looking question window. But that’s another story.

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.

70
Q

What are anonymous functions ?

A
function ask(question, yes, no) {
  if (confirm(question)) yes()
  else no();
}

ask(
“Do you agree?”,
function() { alert(“You agreed.”); },
function() { alert(“You canceled the execution.”); }
);
Here, functions are declared right inside the ask(…) call. They have no name, and so are called anonymous. Such functions are not accessible outside of ask (because they are not assigned to variables), but that’s just what we want here.

71
Q

Give a brief difference between function declaration and function expression.

A

The more subtle difference is when a function is created by the JavaScript engine.

A Function Expression is created when the execution reaches it and is usable only from that moment.

Once the execution flow passes to the right side of the assignment let sum = function… – here we go, the function is created and can be used (assigned, called, etc. ) from now on.

Function Declarations are different.

A Function Declaration can be called earlier than it is defined.

72
Q

Can we call a function before it is defined in JS ? if yes, then how ?

A

A “Function Declaration” can be called earlier than it is defined.

For example, a global Function Declaration is visible in the whole script, no matter where it is.

That’s due to internal algorithms. When JavaScript prepares to run the script, it first looks for global Function Declarations in it and creates the functions. We can think of it as an “initialization stage”.

And after all Function Declarations are processed, the code is executed. So it has access to these functions.

For example, this works:

sayHi(“John”); // Hello, John

function sayHi(name) {
  alert( `Hello, ${name}` );
}
The Function Declaration sayHi is created when JavaScript is preparing to start the script and is visible everywhere in it.

…If it were a Function Expression, then it wouldn’t work:

sayHi(“John”); // error!

let sayHi = function(name) {  // (*) no magic any more
  alert( `Hello, ${name}` );
};
Function Expressions are created when the execution reaches them. That would happen only in the line (*). Too late.
73
Q

let age = prompt(“What is your age?”, 18);

// conditionally declare a function
if (age < 18) {
  function welcome() {
    alert("Hello!");
  }

} else {

  function welcome() {
    alert("Greetings!");
  }

}

// ...use it later
welcome();
A

// Error: welcome is not defined

In strict mode, when a Function Declaration is within a code block, it’s visible everywhere inside that block. But not outside of it.

For instance, let’s imagine that we need to declare a function welcome() depending on the age variable that we get during runtime. And then we plan to use it some time later.

If we use Function Declaration, it won’t work as intended:
That’s because a Function Declaration is only visible inside the code block in which it resides.

74
Q

let age = prompt(“What is your age?”, 18);

let welcome;

if (age < 18) {

welcome = function() {
alert(“Hello!”);
};

} else {

welcome = function() {
alert(“Greetings!”);
};

}

welcome();

A

welcome() runs at the end

it works because, we have used function expression which makes the function available outside the scope

75
Q

When to choose Function Declaration versus Function Expression?

A

As a rule of thumb, when we need to declare a function, the first to consider is Function Declaration syntax. It gives more freedom in how to organize our code, because we can call such functions before they are declared.

That’s also better for readability, as it’s easier to look up function f(…) {…} in the code than let f = function(…) {…};. Function Declarations are more “eye-catching”.

…But if a Function Declaration does not suit us for some reason, or we need a conditional declaration (we’ve just seen an example), then Function Expression should be used.

76
Q

What is the syntax for arrow functions ?

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.
77
Q

how we can dynamically create functions using arrow function syntax ?

A

let age = prompt(“What is your age?”, 18);

let welcome = (age < 18) ?
() => alert(‘Hello’) :
() => alert(“Greetings!”);

welcome();

78
Q

What are multiline arrow functions ?

A

The examples above took arguments from the left of => and evaluated the right-side expression with them.

Sometimes we need something a little bit more complex, like multiple expressions or statements. It is also possible, but we should enclose them in curly braces. Then use a normal return within them.

Like this:

let sum = (a, b) => {  // the curly brace opens a multiline function
  let result = a + b;
  return result; // if we use curly braces, then we need an explicit "return"
};

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