Control Flow and Error Handling Flashcards

1
Q

What is a block statement?

A

The most basic statement is a block statement, which is used to group statements. The block is delimited by a pair of curly brackets {}:

{
  statement1;
  statement2;
  // …
  statementN;
}

Block statements are commonly used with control flow statements (if, for, while).

while (x < 10) {
  x++;
}

Here, { x++; } is the block statement.

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

What is a conditional statement?

A

A conditional statement is a set of commands that executes if a specified condition is true. JavaScript supports two conditional statements: if...else and switch.

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

if...else statement

A

Use the if statement to execute a statement if a logical condition is true. Use the optional else clause to execute a statement if the condition is false.

An if statement looks like this:

if (condition) {
  statement1;
} else {
  statement2;
}

Here, the condition can be any expression that evaluates to true or false. (See Boolean for an explanation of what evaluates to true and false.)

If condition evaluates to true, statement_1 is executed. Otherwise, statement_2 is executed. statement_1 and statement_2 can be any statement, including further nested if statements.

You can also compound the statements using else if to have multiple conditions tested in sequence, as follows:

if (condition1) {
  statement1;
} else if (condition2) {
  statement2;
} else if (conditionN) {
  statementN;
} else {
  statementLast;
}

In the case of multiple conditions, only the first logical condition which evaluates to true will be executed. To execute multiple statements, group them within a block statement ({ /* … */ }).

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

Best practices of if...else statements

A
  • Use block statements—especially when nesting if statements:
if (condition) {
  // Statements for when condition is true
  // …
} else {
  // Statements for when condition is false
  // …
}
  • don’t have if...else statements with an assignment like x = y as a condition:
if (x = y) {
  // statements here
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What are falsy values?

A

A falsy value in JavaScript is a value that is considered false when encountered in a Boolean context. JavaScript uses type conversion to coerce any value to a Boolean in contexts that require it, such as conditionals and loops.

The following values evaluate to false in Boolean contexts:

  • null - The keyword null — the absence of any value.
  • undefined - undefined — the primitive value.
  • false - The keyword false.
  • NaN - NaN — not a number.
  • 0 - The Number zero, also including 0.0, 0x0, etc.
  • -0 - The Number negative zero, also including -0.0, -0x0, etc.
  • 0n - The BigInt zero, also including 0x0n, etc. Note that there is no BigInt negative zero — the negation of 0n is 0n.
  • "" - Empty string value, also including ‘’ and ``.

Examples:

if (false) {
  // Not reachable
}

if (null) {
  // Not reachable
}

if (undefined) {
  // Not reachable
}

if (0) {
  // Not reachable
}

if (-0) {
  // Not reachable
}

if (0n) {
  // Not reachable
}

if (NaN) {
  // Not reachable
}

if ("") {
  // Not reachable
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

switch statement

A

A switch statement in JavaScript allows a program to evaluate an expression and attempt to match the expression’s value to a case label. If a match is found, the program executes the associated statements.

A switch statement looks like this:

switch (expression) {
  case label1:
    statements1;
    break;
  case label2:
    statements2;
    break;
  // …
  default:
    statementsDefault;
}

JavaScript evaluates the above switch statement as follows:

  • The program first looks for a case clause with a label matching the value of expression and then transfers control to that clause, executing the associated statements.
  • If no matching label is found, the program looks for the optional default clause:
    • If a default clause is found, the program transfers control to that clause, executing the associated statements.
    • If no default clause is found, the program resumes execution at the statement following the end of switch.
      (By convention, the default clause is written as the last clause, but it does not need to be so.)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the role of the break statement in a switch case?

A

The break statement in a switch case ensures that the program breaks out of the switch once the matched statement is executed, and then continues execution at the statement following the switch. If break is omitted, the program continues execution with the next case in the switch statement.

Example:

switch (fruitType) {
  case "Oranges":
    console.log("Oranges are $0.59 a pound.");
    break;
  case "Apples":
    console.log("Apples are $0.32 a pound.");
    break;
  case "Bananas":
    console.log("Bananas are $0.48 a pound.");
    break;
  case "Cherries":
    console.log("Cherries are $3.00 a pound.");
    break;
  case "Mangoes":
    console.log("Mangoes are $0.56 a pound.");
    break;
  case "Papayas":
    console.log("Mangoes and papayas are $2.79 a pound.");
    break;
  default:
    console.log(`Sorry, we are out of ${fruitType}.`);
}
console.log("Is there anything else you'd like?");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What happens if a break statement is omitted in a switch case?

A

If a break statement is omitted in a switch case, the program does not break out of the switch after executing the matched statement. Instead, it continues execution with the next case in the switch statement.

Here is an example:

let fruit = 'Apple';

switch(fruit) {
    case 'Apple':
        console.log('Apple case');
        // No break statement here, so execution would fall through to the next case if 'Apple' was the fruit
    case 'Banana':
        console.log('Banana case');
}

// Output: 'Apple caseBanana case'
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

On a switch, will the default case execute if no break statement is added?

A

No, the default case will not execute just because a break statement is omitted from a case clause.

In a switch statement, the default case will only execute if none of the case expressions match the switch expression.

If a break statement is omitted from a case clause, the code execution will “fall through” to the next case clause, not the default case. If none of the case clauses match the switch expression, then the default case will execute, regardless of whether break statements are included or not.

Here is an example:

let fruit = 'Banana';

switch(fruit) {
    case 'Apple':
        console.log('Apple case');
        // No break statement here, so execution would fall through to the next case if 'Apple' was the fruit
    case 'Banana':
        console.log('Banana case');
    default:
        console.log('Default case');
}

// Output: 'Banana case'

In this example, the default case does not execute, even though the ‘Apple’ case does not have a break statement. The default case will only execute if fruit is not ‘Apple’ or ‘Banana’.

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

Ternary operator

A

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.

Syntax

condition ? exprIfTrue : exprIfFalse

Parameters

  • condition - An expression whose value is used as a condition.
  • exprIfTrue - An expression which is executed if the condition evaluates to a truthy value (one which equals or can be converted to true).
  • exprIfFalse - An expression which is executed if the condition is falsy (that is, has a value which can be converted to false).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Can the ternary operator be chained?

A

Yes, the ternary operator is right-associative, which means it can be “chained” in the following way, similar to an if … else if … else if … else chain:

function example() {
  return condition1 ? value1
    : condition2 ? value2
    : condition3 ? value3
    : value4;
}

This is equivalent to the following if...else chain.

function example() {
  if (condition1) {
    return value1;
  } else if (condition2) {
    return value2;
  } else if (condition3) {
    return value3;
  } else {
    return value4;
  }
}

“Conditional chains” (MDN Web Docs). Retrieved November 13, 2023.

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

How can you throw a exception in JavaScript

A

The throw statement in JavaScript is used to throw an exception. It allows developers to create custom error messages which can make debugging more efficient.

Example:

throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
  toString() {
    return "I'm an object!";
  },
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What types of expressions can be thrown in JavaScript?

A

In JavaScript, you can throw any expression, not just expressions of a specific type. This could include strings, numbers, booleans, or even objects.

throw "Error2"; // String type
throw 42; // Number type
throw true; // Boolean type
throw {
  toString() {
    return "I'm an object!";
  },
};
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What is the purpose of the try...catch statement in JavaScript?

A

The try...catch statement in JavaScript is used to handle exceptions. It marks a block of statements to try, and specifies responses should an exception be thrown. If any exception occurs in the try block, control is immediately passed to the catch block.

Example:

function getMonthName(mo) {
  mo--; // Adjust month number for array index (so that 0 = Jan, 11 = Dec)
  const months = [
    "Jan", "Feb", "Mar", "Apr", "May", "Jun",
    "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
  ];
  if (months[mo]) {
    return months[mo];
  } else {
    throw new Error("InvalidMonthNo"); // throw keyword is used here
  }
}

try {
  // statements to try
  monthName = getMonthName(myMonth); // function could throw exception
} catch (e) {
  monthName = "unknown";
  logMyErrors(e); // pass exception object to error handler (i.e. your own function)
}

The previous example uses a try...catch statement. The example calls a function that retrieves a month name from an array based on the value passed to the function. If the value does not correspond to a month number (1 – 12), an exception is thrown with the value InvalidMonthNo and the statements in the catch block set the monthName variable to unknown.

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

What happens when an exception is thrown within a try block in JavaScript?

A

If an exception is thrown within a try block in JavaScript, control immediately shifts to the catch block. The catch block contains statements specifying what to do when an exception is encountered.

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

What happens if no exception is thrown in the try block?

A

If no exception is thrown in the try block, the catch block is skipped. Execution continues with the next block of code after the try...catch statement.

17
Q

What is the purpose of the catch block in JavaScript?

A

In JavaScript, the catch block is used to handle exceptions that may be generated in the try block. It specifies an identifier that holds the value specified by the throw statement, which can be used to get information about the exception that was thrown.

catch (catchID) {
  statements
}
18
Q

What is the lifespan of the identifier in a catch block?

A

The identifier in a catch block is created when the catch block is entered and only lasts for the duration of the catch block. Once the catch block finishes executing, the identifier no longer exists.

19
Q

What is the purpose of the finally block in JavaScript?

A

In JavaScript, the finally block contains statements to be executed after the try and catch blocks, regardless of whether an exception was thrown or not. It’s used to complete any necessary cleanup, such as releasing resources that the script may have tied up.

Example:

openMyFile();
try {
  writeMyFile(theData); // This may throw an error
} catch (e) {
  handleError(e); // If an error occurred, handle it
} finally {
  closeMyFile(); // Always close the resource
}
20
Q

What happens if the finally block returns a value in JavaScript?

A

If the finally block returns a value in JavaScript, this value becomes the return value of the entire try...catch...finally block, regardless of any return statements in the try and catch blocks.

Example:

function f() {
  try {
    console.log(0);
    throw "bogus";
  } catch (e) {
    console.log(1);
    // This return statement is suspended
    // until finally block has completed
    return true;
  } finally {
    console.log(3);
    return false; // overwrites the previous "return"
  }
  // "return false" is executed now
  console.log(5); // not reachable
}
console.log(f()); // 0, 1, 3, false

Overwriting of return values by the finally block also applies to exceptions thrown or re-thrown inside of the catch block:

function f() {
  try {
    throw "bogus";
  } catch (e) {
    console.log('caught inner "bogus"');
    // This throw statement is suspended until
    // finally block has completed
    throw e;
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  console.log(f());
} catch (e) {
  // this is never reached!
  // while f() executes, the `finally` block returns false,
  // which overwrites the `throw` inside the above `catch`
  console.log('caught outer "bogus"');
}

// Logs:
// caught inner "bogus"
// false
21
Q

What does the finally block do when an exception is thrown?

A

If an exception is thrown, the finally block will still execute. This means that even if no catch block handles the thrown exception, the statements in the finally block will still be run. It ensures that your script can handle failures gracefully.

22
Q

What happens if you add a return statement inside a finally block?

A

If the finally block returns a value, this value becomes the return value of the entire try-catch-finally statement, regardless of any return statements in the try and catch blocks. This includes exceptions thrown inside of the catch block:

(() => {
  try {
    try {
      throw new Error("oops");
    } catch (ex) {
      console.error("inner", ex.message);
      throw ex;
    } finally {
      console.log("finally");
      return;
    }
  } catch (ex) {
    console.error("outer", ex.message);
  }
})();

// Logs:
// "inner" "oops"
// "finally"

The outer "oops" is not thrown because of the return in the finally block. The same would apply to any value returned from the catch block.

23
Q

What will this code log?

try {
  try {
    throw new Error("oops");
  } finally {
    console.log("finally");
  }
} catch (ex) {
  console.error("outer", ex.message);
}
A
// Logs:
// "finally"
// "outer" "oops"
24
Q

How can you make sure your scripts finishes gracefully even if it throws an exception?

A

The finally block will execute whether or not an exception is thrown. If an exception is thrown, however, the statements in the finally block execute even if no catch block handles the exception that was thrown.

You can use the finally block to make your script fail gracefully when an exception occurs. For example, you may need to release a resource that your script has tied up.

openMyFile();
try {
  writeMyFile(theData); // This may throw an error
} catch (e) {
  handleError(e); // If an error occurred, handle it
} finally {
  closeMyFile(); // Always close the resource
}
25
Q

What will this code log?

function f() {
  try {
    throw "bogus";
  } catch (e) {
    console.log('caught inner "bogus"');
    throw e;
  } finally {
    return false;
  }
}

try {
  console.log(f());
} catch (e) {
  console.log('caught outer "bogus"');
}
A
function f() {
  try {
    throw "bogus";
  } catch (e) {
    console.log('caught inner "bogus"');
    // This throw statement is suspended until
    // finally block has completed
    throw e;
  } finally {
    return false; // overwrites the previous "throw"
  }
  // "return false" is executed now
}

try {
  console.log(f());
} catch (e) {
  // this is never reached!
  // while f() executes, the `finally` block returns false,
  // which overwrites the `throw` inside the above `catch`
  console.log('caught outer "bogus"');
}
// Logs:
// caught inner "bogus"
// false
26
Q

What is an Error object in JavaScript?

A

The Error object is a built-in object in JavaScript that represents runtime errors, which can be thrown using the throw statement and caught using the catch clause.

27
Q

How can you create an Error object in JavaScript?

A

You can create an Error object in JavaScript by using the Error constructor, like this: let error = new Error(message). The message is an optional string that describes the error.

28
Q

What are the properties of an Error object in JavaScript?

A

Error objects in JavaScript have two main properties: name (sets or returns an error name) and message (sets or returns an error message in the form of a string).

29
Q

What is a TypeError in JavaScript?

A

The TypeError object represents an error when an operation could not be performed, typically (but not exclusively) when a value is not of the expected type.

A TypeError may be thrown when:

  • an operand or argument passed to a function is incompatible with the type expected by that operator or function; or
  • when attempting to modify a value that cannot be changed; or
  • when attempting to use a value in an inappropriate way.
30
Q

What is a ReferenceError in JavaScript?

A

The ReferenceError object represents an error when a variable that doesn’t exist (or hasn’t yet been initialized) in the current scope is referenced.

31
Q

What is a SyntaxError in JavaScript?

A

A SyntaxError is thrown in JavaScript when trying to parse code with a syntax that does not comply with the ECMAScript standard.

32
Q

What is a RangeError in JavaScript?

A

A RangeError is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value.

This can be encountered when:

  • passing a value that is not one of the allowed string values to String.prototype.normalize(), or
  • when attempting to create an array of an illegal length with the Array constructor, or
  • when passing bad values to the numeric methods Number.prototype.toExponential(), Number.prototype.toFixed() or Number.prototype.toPrecision().