Statements Flashcards

1
Q

do…while statement

A

The do…while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

var i = 0;
do {
   i += 1;
} while (i < 5);
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

for statement

A

The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.

for ([initialization]; [condition]; [final-expression])
statement

for (var i = 0; i < 9; i++) {
   console.log(i);
   // more statements
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

for…in statement

A

The for…in statement iterates over the enumerable properties of an object, in original insertion order. For each distinct property, statements can be executed.

var obj = {a: 1, b: 2, c: 3};

for (var prop in obj) {
console.log(obj.${prop} = ${obj[prop]});
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

A for…in loop iterates over the properties of an object in an arbitrary order. Note: for…in should not be used to iterate over an Array where the index order is important.

If you only want to consider properties attached to the object itself, and not its prototypes, use getOwnPropertyNames() or perform a hasOwnProperty() check (propertyIsEnumerable can also be used).

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

for…of statement.

A

The for…of statement creates a loop iterating over iterable objects (including Array, Map, Set, String, TypedArray, arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

let iterable = [10, 20, 30];

for (let value of iterable) {
  value += 1;
  console.log(value);
}
// 11
// 21
// 31
You can use const instead of let too, if you don't reassign the variable inside the block.

let iterable = [10, 20, 30];

for (const value of iterable) {
  console.log(value);
}
// 10
// 20
// 30
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How is a for…in statement different from for…of?

A

The for…in loop will iterate over all enumerable properties of an object.

The for…of syntax is specific to collections, rather than all objects. It will iterate in this manner over the elements of any collection that has a [Symbol.iterator] property.

The following example shows the difference between a for…of loop and a for…in loop.

Object.prototype.objCustom = function() {}; 
Array.prototype.arrCustom = function() {};
let iterable = [3, 5, 7];
iterable.foo = 'hello';

for (let i in iterable) {
console.log(i); // logs 3, 5, 7, “foo”, “arrCustom”, “objCustom”
}

for (let i of iterable) {
console.log(i); // logs 3, 5, 7
}

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

How does a for…of statement iterate a string?

A

let iterable = ‘boo’;

for (let value of iterable) {
  console.log(value);
}
// "b"
// "o"
// "o"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How does a for…of statement iterate a map?

A

let iterable = new Map([[‘a’, 1], [‘b’, 2], [‘c’, 3]]);

for (let entry of iterable) {
  console.log(entry);
}
// ['a', 1]
// ['b', 2]
// ['c', 3]
for (let [key, value] of iterable) {
  console.log(value);
}
// 1
// 2
// 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How does a for…of statement iterate a set?

A

let iterable = new Set([1, 1, 2, 2, 3, 3]);

for (let value of iterable) {
  console.log(value);
}
// 1
// 2
// 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How does a for…of statement iterate function arguments?

A
(function() {
  for (let argument of arguments) {
    console.log(argument);
  }
})(1, 2, 3);
// 1
// 2
// 3
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

switch statement

A

A switch statement first evaluates its expression. It then looks for the first case clause whose expression evaluates to the same value as the result of the input expression (using strict comparison, ===) and transfers control to that clause, executing the associated statements. (If multiple cases match the provided value, the first case that matches is selected, even if the cases are not equal to each other.) If no matching case clause is found, the program looks for the optional default clause, and if found, transfers control to that clause, executing the associated statements. If no default clause is found, the program continues execution at the statement following the end of switch. By convention, the default clause is the last clause, but it does not need to be so.

The optional break statement associated with each case label ensures that the program breaks out of switch once the matched statement is executed and continues execution at the statement following switch. If break is omitted, the program continues execution at the next statement in the switch statement regardless of whether that value matches the expression.

switch (expr) {
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’:
case ‘Papayas’:
console.log(‘Mangoes and papayas are $2.79 a pound.’);
break;
default:
console.log(‘Sorry, we are out of ‘ + expr + ‘.’);
}

console.log(“Is there anything else you’d like?”);

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

while statement

A

The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.

var n = 0;
var x = 0;

while (n < 3) {
n++;
x += n;
}

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

continue statement

A

The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.

In contrast to the break statement, continue does not terminate the execution of the loop entirely: instead,

In a while loop, it jumps back to the condition.
In a for loop, it jumps to the update expression.

var i = 0;
var n = 0;

while (i < 5) {
i++;

if (i === 3) {
continue;
}

n += i;
}

The continue statement can include an optional label that allows the program to jump to the next iteration of a labeled loop statement instead of the current loop. In this case, the continue statement needs to be nested within this labeled statement.

var i = 0;
var j = 8;

checkiandj: while (i < 4) {
i += 1;

checkj: while (j > 4) {
j -= 1;

if ((j % 2) == 0)
  continue checkj;   } }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

break statement

A

The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.

function testBreak(x) {
  var i = 0;
  while (i < 6) {
    if (i == 3) {
      break;
    }
    i += 1;
  }

return i * x;
}

The break statement includes an optional label that allows the program to break out of a labeled statement. The break statement needs to be nested within the referenced label. The labeled statement can be any block statement; it does not have to be preceded by a loop statement.

outer_block: {
  inner_block: {
    console.log('1');
    break outer_block; // breaks out of both inner_block and outer_block
    console.log(':-('); // skipped
  }
  console.log('2'); // skipped
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What are the false values for an if statement?

A

Any value that is not undefined, null, 0, NaN, or the empty string (“”), and any object, including a Boolean object whose value is false, is considered truthy when used as the condition. For example:

var b = new Boolean(false);
if (b) // this condition is truthy
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Label statement

A

The labeled statement can be used with break or continue statements. It is prefixing a statement with an identifier which you can refer to.

Labeled loops or blocks are very uncommon. Oftentimes function calls can be used instead of loop jumps.

var i, j;

loop1:
for (i = 0; i < 3; i++) { //The first for statement is labeled “loop1”
loop2:
for (j = 0; j < 3; j++) { //The second for statement is labeled “loop2”
if (i === 1 && j === 1) {
continue loop1;
}
console.log(‘i = ‘ + i + ‘, j = ‘ + j);
}
}

// Output is:
//   "i = 0, j = 0"
//   "i = 0, j = 1"
//   "i = 0, j = 2"
//   "i = 1, j = 0"
//   "i = 2, j = 0"
//   "i = 2, j = 1"
//   "i = 2, j = 2"
// Notice how it skips both "i = 1, j = 1" and "i = 1, j = 2"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

throw statement

A

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won’t be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

Also note that the throw statement is affected by automatic semicolon insertion (ASI) as no line terminator between the throw keyword and the expression is allowed.

function UserException(message) {
   this.message = message;
   this.name = 'UserException';
}
function getMonthName(mo) {
   mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec)
   var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul',
      'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
   if (months[mo] !== undefined) {
      return months[mo];
   } else {
      throw new UserException('InvalidMonthNo');
   }
}
try {
   // statements to try
   var myMonth = 15; // 15 is out of bound to raise the exception
   var monthName = getMonthName(myMonth);
} catch (e) {
   monthName = 'unknown';
   console.log(e.message, e.name); // pass exception object to err handler
}

The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type ZipCodeFormatException.

/*
 * Creates a ZipCode object.
 *
 * Accepted formats for a zip code are:
 *    12345
 *    12345-6789
 *    123456789
 *    12345 6789
 *
 * If the argument passed to the ZipCode constructor does not
 * conform to one of these patterns, an exception is thrown.
 */
function ZipCode(zip) {
   zip = new String(zip);
   pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
   if (pattern.test(zip)) {
      // zip code value will be the first match in the string
      this.value = zip.match(pattern)[0];
      this.valueOf = function() {
         return this.value
      };
      this.toString = function() {
         return String(this.value)
      };
   } else {
      throw new ZipCodeFormatException(zip);
   }
}
function ZipCodeFormatException(value) {
   this.value = value;
   this.message = 'does not conform to the expected format for a zip code';
   this.toString = function() {
      return this.value + this.message;
   };
}

/*

  • This could be in a script that validates address data
  • for US addresses.
  • /
const ZIPCODE_INVALID = -1;
const ZIPCODE_UNKNOWN_ERROR = -2;
function verifyZipCode(z) {
   try {
      z = new ZipCode(z);
   } catch (e) {
      if (e instanceof ZipCodeFormatException) {
         return ZIPCODE_INVALID;
      } else {
         return ZIPCODE_UNKNOWN_ERROR;
      }
   }
   return z;
}
a = verifyZipCode(95060);         // returns 95060
b = verifyZipCode(9560);          // returns -1
c = verifyZipCode('a');           // returns -1
d = verifyZipCode('95060');       // returns 95060
e = verifyZipCode('95060 1234');  // returns 95060 1234
17
Q

try…catch statement

A

The try statement consists of a try block, which contains one or more statements ({} must always be used, also for single statements), and at least one catch clause or a finally clause, or both. That is, there are three forms of the try statement:

try…catch
try…finally
try…catch…finally
A catch clause contains statements that specify what to do if an exception is thrown in the try block. That is, you want the try block to succeed, and if it does not succeed, you want control to pass to the catch block. If any statement within the try block (or in a function called from within the try block) throws an exception, control immediately shifts to the catch clause. If no exception is thrown in the try block, the catch clause is skipped.

The finally clause executes after the try block and catch clause(s) execute but before the statements following the try statement. It always executes, regardless of whether or not an exception was thrown or caught.

You can nest one or more try statements. If an inner try statement does not have a catch clause, the enclosing try statement’s catch clause is entered.

You also use the try statement to handle JavaScript exceptions. See the JavaScript Guide for more information on JavaScript exceptions.

try {
   throw 'myException'; // generates an exception
}
catch (e) {
   // statements to handle any exceptions
   logMyErrors(e); // pass exception object to error handler
}

Also, finally…

openMyFile();
try {
   // tie up a resource
   writeMyFile(theData);
}
finally {
   closeMyFile(); // always close the resource
}