buy the book to support the author.

Chapter 13. Statements

This chapter covers JavaScript’s statements: variable declarations, loops, conditionals, and others.

Declaring and Assigning Variables

var is used to declare a variable, which creates the variable and enables you to work with it. The equals operator (=) is used to assign a value to it:

  1. var foo;
  2. foo = 'abc';

var also lets you combine the preceding two statements into a single one:

  1. var foo = 'abc';

Finally, you can also combine multiple var statements into one:

  1. var x, y=123, z;

Read more about how variables work in Chapter 16.

The Bodies of Loops and Conditionals

Compound statements such as loops and conditionals have one or more “bodies” embedded—for example, the while loop:

  1. while («condition»)
  2. «statement»

For the body «statement», you have a choice. You can either use a single statement:

  1. while (x >= 0) x--;

or you can use a block (which counts as a single statement):

  1. while (x > 0) {
  2. x--;
  3. }

You need to use a block if you want the body to comprise multiple statements. Unless the complete compound statement can be written in a single line, I recommend using a block.

Loops

This section explores JavaScript’s loop statements.

Mechanisms to Be Used with Loops

The following mechanisms can be used with all loops:

  • break ⟦«label»⟧
  • Exit from a loop.
  • continue ⟦«label»⟧
  • Stop the current loop iteration, and immediately continue with the next one.
  • Labels
  • A label is an identifier followed by a colon. In front of a loop, a label allows you to break or continue that loop even from a loop nested inside of it. In front of a block, you can break out of that block. In both cases, the name of the label becomes an argument of break or continue. Here’s an example of breaking out of a block:
  1. function findEvenNumber(arr) {
  2. loop: { // label
  3. for (var i=0; i<arr.length; i++) {
  4. var elem = arr[i];
  5. if ((elem % 2) === 0) {
  6. console.log('Found: ' + elem);
  7. break loop;
  8. }
  9. }
  10. console.log('No even number found.');
  11. }
  12. console.log('DONE');
  13. }

while

A while loop:

  1. while («condition»)
  2. «statement»

executes statement as long as condition holds. If condition is always true, you get an infinite loop:

  1. while (true) { ... }

In the following example, we remove all elements of an array and log them to the console:

  1. var arr = [ 'a', 'b', 'c' ];
  2. while (arr.length > 0) {
  3. console.log(arr.shift());
  4. }

Here is the output:

  1. a
  2. b
  3. c

do-while

A do-while loop:

  1. do «statement»
  2. while («condition»);

executes statement at least once and then as long as condition holds. For example:

  1. var line;
  2. do {
  3. line = prompt('Enter a number:');
  4. } while (!/^[0-9]+$/.test(line));

for

In a for loop:

  1. for (⟦«init»⟧; ⟦«condition»⟧; ⟦«post_iteration»⟧)
  2. «statement»

init is executed once before the loop, which continues as long as condition is true. You can use var in init to declare variables, but the scope of those variables is always the complete surrounding function. post_iteration is executed after each iteration of the loop. Taking all of this into consideration, the preceding loop is equivalent to the following while loop:

  1. «init»;
  2. while («condition») {
  3. «statement»
  4. «post_iteration»;
  5. }

The following example is the traditional way of iterating over arrays (other possibilities are described in Best Practices: Iterating over Arrays):

  1. var arr = [ 'a', 'b', 'c' ];
  2. for (var i=0; i<arr.length; i++) {
  3. console.log(arr[i]);
  4. }

A for loop becomes infinite if you omit all parts of the head:

  1. for (;;) {
  2. ...
  3. }

for-in

A for-in loop:

  1. for («variable» in «object»)
  2. «statement»

iterates over all property keys of object, including inherited ones. However, properties that are marked as not enumerable are ignored (see Property Attributes and Property Descriptors). The following rules apply to for-in loops:

  • You can use var to declare variables, but the scope of those variables is always the complete surrounding function.
  • Properties can be deleted during iteration.

Best practice: don’t use for-in for arrays

Don’t use for-in to iterate over arrays. First, it iterates over indices, not over values:

  1. > var arr = [ 'a', 'b', 'c' ];
  2. > for (var key in arr) { console.log(key); }
  3. 0
  4. 1
  5. 2

Second, it also iterates over all (nonindex) property keys. The following example illustrates what happens when you add a property foo to an array:

  1. > var arr = [ 'a', 'b', 'c' ];
  2. > arr.foo = true;
  3. > for (var key in arr) { console.log(key); }
  4. 0
  5. 1
  6. 2
  7. foo

Thus, you are better off with a normal for loop or the array method forEach() (see Best Practices: Iterating over Arrays).

Best practice: be careful with for-in for objects

The for-in loop iterates over all (enumerable) properties, including inherited ones. That may not be what you want. Let’s use the following constructor to illustrate the problem:

  1. function Person(name) {
  2. this.name = name;
  3. }
  4. Person.prototype.describe = function () {
  5. return 'Name: '+this.name;
  6. };

Instances of Person inherit the property describe from Person.prototype, which is seen by for-in:

  1. var person = new Person('Jane');
  2. for (var key in person) {
  3. console.log(key);
  4. }

Here is the output:

  1. name
  2. describe

Normally, the best way to use for-in is to skip inherited properties via hasOwnProperty():

  1. for (var key in person) {
  2. if (person.hasOwnProperty(key)) {
  3. console.log(key);
  4. }
  5. }

And here is the output:

  1. name

There is one last caveat: person may have a property hasOwnProperty, which would prevent the check from working. To be safe, you have to refer to the generic method (see Generic Methods: Borrowing Methods from Prototypes) Object.prototype.hasOwnProperty directly:

  1. for (var key in person) {
  2. if (Object.prototype.hasOwnProperty.call(person, key)) {
  3. console.log(key);
  4. }
  5. }

There are other, more comfortable, means for iterating over property keys, which are described in Best Practices: Iterating over Own Properties.

for each-in

This loop exists only on Firefox. Don’t use it.

Conditionals

This section covers JavaScript’s conditional statements.

if-then-else

In an if-then-else statement:

  1. if («condition»)
  2. «then_branch»
  3. else
  4. «else_branch»⟧

then_branch and else_branch can be either single statements or blocks of statements (see The Bodies of Loops and Conditionals).

Chaining if statements

You can chain several if statements:

  1. if (s1 > s2) {
  2. return 1;
  3. } else if (s1 < s2) {
  4. return -1;
  5. } else {
  6. return 0;
  7. }

Note that in the preceding example, all the else branches are single statements (if statements). Programming languages that only allow blocks for else branches need some kind of else-if branch for chaining.

Pitfall: dangling else

The else branch of the following example is called dangling, because it is not clear to which of the two if statements it belongs:

  1. if («cond1») if («cond2») «stmt1» else «stmt2»

Here’s a simple rule: use braces. The preceding snippet is equivalent to the following code (where it is obvious who the else belongs to):

  1. if («cond1») {
  2. if («cond2») {
  3. «stmt1»
  4. } else {
  5. «stmt2»
  6. }
  7. }

switch

A switch statement:

  1. switch («expression») {
  2. case «label1_1»:
  3. case «label1_2»:
  4. ...
  5. «statements1»
  6. break;
  7. case «label2_1»:
  8. case «label2_2»:
  9. ...
  10. «statements2»
  11. break;
  12. ...
  13. default:
  14. «statements_default»
  15. break;⟧⟧
  16. }

evaluates expression and then jumps to the case clause whose label matches the result. If no label matches, switch jumps to the default clause if it exists or does nothing otherwise.

The “operand” after case can be any expression; it is compared via === with the parameter of switch.

If you don’t finish a clause with a terminating statement, execution continues into the next clause. The most frequently used terminating statement is break. But return and throw also work, even though they normally leave more than just the switch statement.

The following example illustrates that you don’t need to break if you use throw or return:

  1. function divide(dividend, divisor) {
  2. switch (divisor) {
  3. case 0:
  4. throw 'Division by zero';
  5. default:
  6. return dividend / divisor;
  7. }
  8. }

In this example, there is no default clause. Therefore, nothing happens if fruit matches none of the case labels:

  1. function useFruit(fruit) {
  2. switch (fruit) {
  3. case 'apple':
  4. makeCider();
  5. break;
  6. case 'grape':
  7. makeWine();
  8. break;
  9. // neither apple nor grape: do nothing
  10. }
  11. }

Here, there are multiple case labels in a row:

  1. function categorizeColor(color) {
  2. var result;
  3. switch (color) {
  4. case 'red':
  5. case 'yellow':
  6. case 'blue':
  7. result = 'Primary color: '+color;
  8. break;
  9. case 'orange':
  10. case 'green':
  11. case 'violet':
  12. result = 'Secondary color: '+color;
  13. break;
  14. case 'black':
  15. case 'white':
  16. result = 'Not a color';
  17. break;
  18. default:
  19. throw 'Illegal argument: '+color;
  20. }
  21. console.log(result);
  22. }

This example demonstrates that the value after case can be an arbitrary expression:

  1. function compare(x, y) {
  2. switch (true) {
  3. case x < y:
  4. return -1;
  5. case x === y:
  6. return 0;
  7. default:
  8. return 1;
  9. }
  10. }

The preceding switch statement looks for a match for its parameter true by going through the case clauses. If one of the case expressions evaluates to true, the corresponding case body is executed.Therefore, the preceding code is equivalent to the following if statement:

  1. function compare(x, y) {
  2. if (x < y) {
  3. return -1;
  4. } else if (x === y) {
  5. return 0;
  6. } else {
  7. return 1;
  8. }
  9. }

You normally should prefer the latter solution; it is more self-explanatory.

The with Statement

This section explains how the with statement works in JavaScript and why its use is discouraged.

Syntax and Semantics

The syntax of the with statement is as follows:

  1. with («object»)
  2. «statement»

It turns the properties of object into local variables for statement. For example:

  1. var obj = { first: 'John' };
  2. with (obj) {
  3. console.log('Hello '+first); // Hello John
  4. }

Its intended use is to avoid redundancy when accessing an object several times. The following is an example of code with redundancies:

  1. foo.bar.baz.bla = 123;
  2. foo.bar.baz.yadda = 'abc';

with makes this shorter:

  1. with (foo.bar.baz) {
  2. bla = 123;
  3. yadda = 'abc';
  4. }

The with Statement Is Deprecated

The use of the with statement is generally discouraged (the next section explains why). For example, it is forbidden in strict mode:

  1. > function foo() { 'use strict'; with ({}); }
  2. SyntaxError: strict mode code may not contain 'with' statements

Techniques for avoiding the with statement

Avoid code like this:

  1. // Don't do this:
  2. with (foo.bar.baz) {
  3. console.log('Hello '+first+' '+last);
  4. }

Instead, use a temporary variable with a short name:

  1. var b = foo.bar.baz;
  2. console.log('Hello '+b.first+' '+b.last);

If you don’t want to expose the temporary variable b to the currentscope, you can use an IIFE (see Introducing a New Scope via an IIFE):

  1. (function () {
  2. var b = foo.bar.baz;
  3. console.log('Hello '+b.first+' '+b.last);
  4. }());

You also have the option of making the object that you want to access a parameter of the IIFE:

  1. (function (b) {
  2. console.log('Hello '+b.first+' '+b.last);
  3. }(foo.bar.baz));

The Rationale for the Deprecation

To understand why with is deprecated, look at the following example and notice how the function’s argument completely changes how it works:

  1. function logMessage(msg, opts) {
  2. with (opts) {
  3. console.log('msg: '+msg); // (1)
  4. }
  5. }

If opts has a property msg, then the statement in line (1) doesn’t access the parameter msg anymore. It accesses the property:

  1. > logMessage('hello', {}) // parameter msg
  2. msg: hello
  3. > logMessage('hello', { msg: 'world' }) // property opts.msg
  4. msg: world

There are three problems that the with statement causes:

  • Performance suffers
  • Variable lookup becomes slower, because an object is temporarily inserted into the scope chain.
  • Code becomes less predictable
  • You cannot determine what an identifier refers to by looking at its syntactic surroundings (its lexical context). According to Brendan Eich, that was the actual reason why with was deprecated, not performance considerations:

with violates lexical scope, making program analysis (e.g. for security) hard to infeasible.

  • Minifiers (described in Chapter 32) can’t shorten variable names
  • Inside a with statement, you can’t statically determine whether a name refers to a variable or a property. Only variables can be renamed by minifiers.

Here is an example of with making code brittle:

  1. function foo(someArray) {
  2. var values = ...; // (1)
  3. with (someArray) {
  4. values.someMethod(...); // (2)
  5. ...
  6. }
  7. }
  8. foo(myData); // (3)

You can prevent the function call in line (3) from working, even if you don’t have access to the array myData.

How? By adding a property values to Array.prototype. For example:

  1. Array.prototype.values = function () {
  2. ...
  3. };

Now the code in line (2) calls someArray.values.someMethod() instead of values.someMethod(). The reason is that, inside the with statement, values now refers to someArray.values and not the local variable from line (1) anymore.

This is not just a thought experiment: the array method values() was added to Firefox and broke the TYPO3 content management system. Brandon Benvie figured out what went wrong.

The debugger Statement

The syntax for the debugger statement is as follows:

  1. debugger;

If a debugger is active, this statement functions as a breakpoint; if not, it has no observable effect.