Control structures
JavaScript has a similar set of control structures to other languages in the C family. Conditional statements are supported by if and else; you can chain them together:
let name = "kittens";
if (name === "puppies") {
name += " woof";
} else if (name === "kittens") {
name += " meow";
} else {
name += "!";
}
name === "kittens meow";
JavaScript doesn't have elif, and else if is really just an else branch comprised of a single if statement.
JavaScript has while loops and do...while loops. The first is good for basic looping; the second is for loops where you wish to ensure that the body of the loop is executed at least once:
while (true) {
// an infinite loop!
}
let input;
do {
input = get_input();
} while (inputIsNotValid(input));
JavaScript's for loop is the same as that in C and Java: it lets you provide the control information for your loop on a single line.
for (let i = 0; i < 5; i++) {
// Will execute 5 times
}
JavaScript also contains two other prominent for loops: for...of, which iterates over iterables, most notably arrays, and for...in, which visits all enumerable properties of an object.
for (const value of array) {
// do something with value
}
for (const property in object) {
// do something with object property
}
The switch statement can be used for multiple branches based on equality checking.
switch (action) {
case "draw":
drawIt();
break;
case "eat":
eatIt();
break;
default:
doNothing();
}
Similar to C, case clauses are conceptually the same as labels, so if you don't add a break statement, execution will "fall through" to the next level. However, they are not actually jump tables — any expression can be part of the case clause, not just string or number literals, and they would be evaluated one-by-one until one equals the value being matched. Comparison takes place between the two using the === operator.
Unlike some languages like Rust, control-flow structures are statements in JavaScript, meaning you can't assign them to a variable, like const a = if (x) { 1 } else { 2 }.
JavaScript errors are handled using the try...catch statement.
try {
buildMySite("./website");
} catch (e) {
console.error("Building site failed:", e);
}
Errors can be thrown using the throw statement. Many built-in operations may throw as well.
function buildMySite(siteDirectory) {
if (!pathExists(siteDirectory)) {
throw new Error("Site directory does not exist");
}
}
In general, you can't tell the type of the error you just caught, because anything can be thrown from a throw statement. However, you can usually assume it's an Error instance, as is the example above. There are some subclasses of Error built-in, like TypeError and RangeError, that you can use to provide extra semantics about the error. There's no conditional catch in JavaScript — if you only want to handle one type of error, you need to catch everything, identify the type of error using instanceof, and then rethrow the other cases.
try {
buildMySite("./website");
} catch (e) {
if (e instanceof RangeError) {
console.error("Seems like a parameter is out of range:", e);
console.log("Retrying...");
buildMySite("./website");
} else {
// Don't know how to handle other error types; throw them so
// something else up in the call stack may catch and handle it
throw e;
}
}
If an error is uncaught by any try...catch in the call stack, the program will exit.
For a comprehensive list of control flow statements, see the reference section.