Control Flow and Error Handling Flashcards
What is a block statement?
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.
“Block statement” (developer.mozilla.org). Retrieved July 14, 2023.
What is a conditional statement?
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
.
“Conditional statements” (developer.mozilla.org). Retrieved July 14, 2023.
if...else
statement
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 ({ /* … */ }
).
“if…else statement” (developer.mozilla.org). Retrieved July 14, 2023.
Best practices of if...else
statements
- 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 likex = y
as a condition:
if (x = y) { // statements here }
“if…else statement” (developer.mozilla.org). Retrieved July 14, 2023.
What are falsy values?
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 including0x0n
, etc. Note that there is noBigInt
negative zero — the negation of0n
is0n
. -
""
- 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 }
“Falsy - MDN Web Docs Glossary: Definitions of Web-related terms | MDN” (developer.mozilla.org). Retrieved July 14, 2023.
switch
statement
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 alabel
matching the value ofexpression
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 ofswitch
.
(By convention, thedefault
clause is written as the last clause, but it does not need to be so.)
- If a
“switch statement” (developer.mozilla.org). Retrieved July 17, 2023.
What is the role of the break
statement in a switch case
?
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?");
“switch statement” (developer.mozilla.org). Retrieved July 17, 2023.
What happens if a break
statement is omitted in a switch case
?
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'
“switch statement” (developer.mozilla.org). Retrieved July 17, 2023.
On a switch
, will the default
case
execute if no break
statement is added?
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’.
“switch statement” (developer.mozilla.org). Retrieved July 17, 2023.
Ternary operator
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).
“Conditional (ternary) operator - JavaScript | MDN” (MDN Web Docs). Retrieved November 13, 2023.
Can the ternary operator be chained?
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 can you throw a exception in JavaScript
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!"; }, };
“throw statement” (developer.mozilla.org). Retrieved July 18, 2023.
What types of expressions can be thrown in JavaScript?
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!"; }, };
“throw statement” (developer.mozilla.org). Retrieved July 18, 2023.
What is the purpose of the try...catch
statement in JavaScript?
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
.
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What happens when an exception is thrown within a try
block in JavaScript?
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.
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What happens if no exception is thrown in the try
block?
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.
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What is the purpose of the catch
block in JavaScript?
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 }
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What is the lifespan of the identifier in a catch
block?
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.
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What is the purpose of the finally
block in JavaScript?
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 }
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What happens if the finally
block returns a value in JavaScript?
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
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What does the finally
block do when an exception is thrown?
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.
“try…catch statement” (developer.mozilla.org). Retrieved July 18, 2023.
What happens if you add a return
statement inside a finally
block?
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.
“Returning from a finally block” (developer.mozilla.org). Retrieved July 25, 2023.
What will this code log?
try { try { throw new Error("oops"); } finally { console.log("finally"); } } catch (ex) { console.error("outer", ex.message); }
// Logs: // "finally" // "outer" "oops"
“Nested try blocks” (developer.mozilla.org). Retrieved July 25, 2023.
How can you make sure your scripts finishes gracefully even if it throws an exception?
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 }
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"'); }
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
“try…catch statement” (developer.mozilla.org). Retrieved July 25, 2023.
What is an Error
object in JavaScript?
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.
“Error - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.
How can you create an Error
object in JavaScript?
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.
“Error - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.
What are the properties of an Error
object in JavaScript?
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).
“Error - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.
What is a TypeError
in JavaScript?
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.
“TypeError - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.
What is a ReferenceError
in JavaScript?
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.
“ReferenceError - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.
What is a SyntaxError
in JavaScript?
A SyntaxError
is thrown in JavaScript when trying to parse code with a syntax that does not comply with the ECMAScript standard.
“SyntaxError - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.
What is a RangeError
in JavaScript?
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()
orNumber.prototype.toPrecision()
.
“RangeError - JavaScript | MDN” (developer.mozilla.org). Retrieved July 25, 2023.