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.