by Gordon Mccomb

How to use JavaScript statements in your programs

how-to
May 01, 202417 mins
JavaScriptProgramming LanguagesSoftware Development

Developers use statements to control the overall program flow, including variable declarations, conditional operations, and iterative processes. Here's how to write JavaScript statements.

Image of a person typing on a keyboard. Text, speech, typing.
Credit: Tero Vesalainen/Shutterstock

JavaScript statements control the overall flow of JavaScript programs. Statements are used to declare variables and manage iterative processes, and they can also be used to declare classes and functions.

Unlike properties, methods, and events, which are inseparable from the object that owns them, statements work independently. That means you can use a statement in any context, whether you’re programming a client-side or server-side application. As a language, JavaScript supports relatively few statements—just enough to construct functional applications.

This article covers a sample of JavaScript statements you are most likely to see and use in your JavaScript programs. A few of the statements included here—namely, comment, let, and new—are declarations. Whether declarations can also be statements is a matter of debate, but they are generally treated as such in programs.

JavaScript statements and how to use them

The following JavaScript statements are introduced with code examples:

  • //
  • for
  • for…in
  • if…else
  • function
  • new
  • return
  • this
  • var, let, const
  • while
  • do…while
  • with
  • break
  • continue
  • switch
  • try, catch, finally, throw

Comment (//)

The comment (//) syntax tells JavaScript that you want to include explanatory comments in your program. The comment ends at the first hard return (line break) following the statement. JavaScript places no limit on the length of a comment, as long as there is no hard return before it ends. JavaScript assumes any text after a hard return is valid code. Here’s an example of a comment in code:


// This is a simple comment

Though the comment wraps to the second line, the first line ends with a “soft return” in the text editing program. No hard return character is inserted.

You can place the // characters anywhere on a line. JavaScript will treat all the text on that line following the // as a comment:


MyVariable="This is a test" // assigns text variable MyVariable

Comments are ignored when a script is run, so they do not greatly affect the speed of execution. Most build pipelines will strip comments out before sending code over the wire.

When writing long comments, it’s better to use the alternative commenting syntax of /* and */. Text between these characters is treated as a comment:


/* This section checks to see if the Enter key is pressed…

then continues on */

Alternatively, you can start each new line with a //:


// This section checks to see if the Enter key is pressed…

// then continues on

Comments are not technically considered statements, but how we use them is similar, so I’ve included the syntax here.

for

Of all the elements of structured programming, for is a champion. It gives developers the ability to perform actions repeatedly, based on a condition. Along with if, for is a foundational component of all software. 

The for statement repeats a block of instructions one or more times. The number of iterations is controlled by values supplied as arguments. Here’s the syntax of a for statement:


for (InitVal; Test; Increment) 
  • InitVal is the starting value of the for loop. It is often 0 or 1, but it can be any number. InitVal is an expression that establishes the initial value and assigns it to a variable. For example, count=0 or i=1.
  • Test is the expression used by the for statement to control the number of times the loop iterates. As long as the Test expression is true, the loop continues. When the Test expression proves false, the loop ends. As an example, count<10 is true as long as the value in the count variable is less than 10.
  • Increment indicates how you want the for loop to count—by ones, twos, fives, tens, and so on. This is also an expression and usually takes the form of countVar++, where CountVar is the name of the variable first assigned in the InitVal. As an example, count++ increases the value of the count variable by one for each iteration.

Unlike all the other constructs in JavaScript, the for statement uses semicolons rather than commas to separate its arguments. This is the same as the syntax used in C, C++, and Java.

Here’s an example of a for loop that counts from 1 to 10, stepping one digit at a time. At each iteration, the script inserts some text and begins a new line. The JavaScript you wish to repeat is enclosed in braces ({ }) following the for statement; this forms the for statement block. You can provide one line or many inside the brace characters:


for (count=1; count<=10; count++) {
    console.log("Iteration: "+count);
}

Remember that count is the variable name used to store the for loop counter. The loop starts with 1 and proceeds to 10. The test expression is count<=10, which reads:


Count is less than or equal to 10

As long as this expression is true, the for loop continues. Do note that the Increment argument is also an expression. In this example, Increment uses the count variable to increment the for loop by 1 for each iteration. There’s no law that you must increment by ones, however. Here’s an example that counts by tens, from 10 to 100:


for (count=1; count<101; count+=10) {
    document.write ("Iteration: "+count);
}

With the for loop in your pocket, you have a versatile, lasting tool for a lifetime of travels in the world of programming. 

for…in

The for…in statement is a special version of the for statement. This syntax is used to display the property names and/or contents of objects. This is common when dealing with JSON data objects. 

Unlike the for statement, for…in doesn’t use incrementing tests or other expressions. You provide the name of a holding variable (the name of the variable is up to you) and the object you want to use. Here’s the basic syntax:


for (iterator in object) {
  statements
}
  • iterator is the name of a variable.
  • object is the object you wish to examine.
  • statements are one or more JavaScript instructions you wish to execute for each property returned by the for…in loop.

Here’s a simple example of using for…in:


const person = {
  name: "Harsha Suryanarayana",
  occupation: "Software Engineer"
};

for (let key in person) {
  console.log(`${key}: ${person[key]}`);
}

This outputs the name and occupation labels with their values.

if…else

The if statement, along with its optional else, is used to build an “if conditional” expression. It says: If something is true, then do this. The if statement is called a conditional expression because it tests for a specific condition. The following rules apply when using if…else statements:

  • If the expression is true, the script performs the instructions following the if statement.
  • If the expression is false, the script jumps to the instructions that follow the else statement.
  • If there is no else statement, the script jumps past the if statement entirely and continues from there.

Like for, if is a fundamental component of software. Developers use it to branch the control flow in a way that is clear and easy to understand.

The syntax for if is:


if (expression)

The result of the if expression is always true or false. The following syntax, without brackets enclosing the blocks, is acceptable when there’s only one instruction following the if and else statements:


if (test > 10)
    console.log(‘more than 10’);
else
    console.log(‘less than 10’);

You could write this even more compactly, as:


if (test > 10) console.log("more than 10"); else console.log("less than 10");

Should more than one instruction follow the if or else statement, you must use curly brackets (braces) to define an if statement block. With braces in place, JavaScript knows to execute all the instructions within the block:


if (test > 10) {
  count = 1;
  console.log("more than 10");
} else {
  count = 0; 
  console.log("less than 10");
}

You can also chain many if-else-if statements together:


if (test > 10) {
  console.log("more than 10"); 
} else if (test == 10) {
  console.log("10"); 
} else {
  console.log("less than 10");

function

Functions are another fundamental part of structured programming. The function statement lets you create your own user-defined functions, as well as user-defined objects and methods for them. Functions are self-contained routines that can be “called” elsewhere within your JavaScript code. Along with loops and conditionals, functions are an essential means of organizing software.  

JavaScript has a very powerful function system, where functions can be referenced just like any other variable. This is known as “first-class functions” and it’s a big source of JavaScript’s power and flexibility.

Here’s an example of the basic use of a function:


function add(number1, number2){
  return number1 + number2;
}

You can call this function like so: add(10, 5).

In a way, functions are like customized extensions of the JavaScript language. They can be used anywhere you would use a statement, and their return value is similar to a variable: console.log(add(10,5)) will output the number 15 to the console.

Another syntax for defining functions is:


let multiply = function(number1, number2){ 
return number1 * number2; 
}

Both of these syntaxes are common and acceptable. You’ll also find the function statement inline in JSON literals:


let json = { 
    subtract: function (number1, number2){ 
        return number1 - number2;
    } 
}

We could call this function with the dot operator: json.subtract(10,5).

new

The new statement is primarily used to create a new object:


let myInstance  = new MyObject(params);
  • myInstance is the name of the new object instance. Acceptable names are the same as for JavaScript variables. You can consider the created object as a JavaScript variable. (Objects are in fact custom data types.)
  • Object types (like MyObject) are usually CamelCase, with the first letter capitalized, whereas object instances (like myInstance) are usually camelCase, with the first letter being lowercase.
  • params are one or more parameters that you pass to the object function, if needed.

There are several ways to create an object type in JavaScript. For example, we could use the class syntax and the new statement to create an instance:


class Person {
  constructor(name) {
    this.name = name;
  }
}

let person = new Person("John");

return

The return statement is used to mark the end of a function, optionally returning a value. When JavaScript encounters this statement, it “returns” to the spot where the function was called. The return statement can be used with and without a return value.

  • If a value is included, the function returns that value.
  • If no value is included, the function returns undefined.

The return statement may not be used outside of a function. JavaScript reports an error if you attempt to use return outside a function. Here are two examples of return, with and without a value:


function myFunc() { var outString = "This is a test"; return OutString; }
function myFunc() { outString = "This is a test"; return; }

In modern JavaScript, you have some interesting options for handling return values. For example, you can return an object and use destructuring to “explode” it into discrete values:


function getUserInfo(name) {
  return { name, age: 25, city: "New York" };
}
const { name, age, city } = getUserInfo("Alice");
console.log(`${name} is ${age} years old and lives in ${city}`);

this

The this keyword (it’s not technically a statement) refers to the current object and is shorthand for using the formal name of the object. Using this gives you a reference to the current “scope” of the code. That is, it gives you a handle on the immediately larger setting where variables are held. There is some nuance to how this behaves and resolves, especially with respect to closures, but in general, if you remember that it refers to the immediate container object, you’ll be okay. 

As a typical example, consider our subtract function from earlier. 


let json = { 
    subtract: function (number1, number2){ 
        console.log("this: " + this);
        return number1 - number2;
    } 
}

In this case, the json object itself will resolve the call to this and so the console output will be: this: [object Object].

var, let, const

The var, let, and const statements are used to declare a variable reference. It is important to note that var is an older style and is generally deprecated in favor of let. This is because var “hoists” the variable to the top of its scope, while let restricts it to the current block. The const statement, meanwhile, makes a variable that the interpreter will not allow to be modified (that is, an “immutable” variable).

Here’s an example:


let myVariable = “foo”;
const myOtherVariable = “bar”;

Now the myOtherVariable reference cannot be changed.

Although const prevents a reference from changing, it doesn’t prevent the internals of an object or array from being changed:


const myArray = {0,1,1,3,4};
myArray[2] = 2; // this is OK

while

The while statement sets up a unique repeating loop that causes the script to repeat a given set of instructions, similar to for. The looping continues for as long as the expression in the while statement is true. When the while statement proves false, the loop is broken and the script continues. Any JavaScript code inside the while statement block—defined by braces (aka curly brackets)—is considered part of the loop and is repeated. Here’s the syntax of the while statement:


while (Expression)  {
    // stuff to repeat
}

In the following example, the while loop is repeated a total of 10 times. With each iteration of the loop, JavaScript prints text to the screen:


count=0;
while (count <10) {
    console.log(“Iteration: ${count}”);
    count++;
}

Here’s how the code in this example works. First, the count variable is set to 0. This is the initial value that will be compared in the while expression, which is count <10, or “count starts at 0.” With each iteration of the loop, text is printed to the screen and the count variable is increased by 1.

The first 10 times the loop is repeated, count <10 is true, so the loop continues. After the tenth trip, the count variable contains the number 10, and the while expression proves false. The loop is broken, and JavaScript skips to the end of the while statement block, which is the portion after the end-brace character.

The while loop is what is known as an entry loop. The test expression appears at the beginning of the loop structure. The contents of a while loop may never be executed, depending on the outcome of the test expression. For example,


Response = prompt ("Please enter a number greater than 1");
count = 1;
while (count <= response) {
    document.write ("count: "+ count + "<BR>");
    count++;
}

In this example, a prompt method asks you to enter a number greater than 1. This number is then used to control the iterations of a while loop. So if you type 5, the loop will repeat five times. The loop continues as long as the while expression—count<=response—remains true. Notice that the count variable starts at 1. In this way, if you enter a 0 in response to the prompt, the loop fails. In that case, the instructions inside the while loop block are never executed (because 1<=0 is false).

do…while

The do…while statement is a newer variant of while. It behaves the same but ensures there is at least one execution of the loop. This is sometimes very useful. In some cases, the logic of your situation clearly demands a do…while, like we see here:


let number = 1; // Starting value

do {
  console.log(`Current number: ${number}`);
  number++;
} while (number <= 5);

with

The with statement is deprecated due to performance and clarity problems. Here’s an example anyway, just in case you ever see one in the wild:


const person = { name: "John", age: 30 };
with (person) {
  console.log(name); // Outputs "John"
  console.log(age); // Outputs 30
}

The statement says: assuming the person object as scope, use the variables name and age

break

The break statement tells JavaScript to exit a “controlled structure” and resume execution at a point after the structure. The break statement is used with structures built using the following commands:

  • for…in
  • while

The break statement is most often used to prematurely end a for loop:


for (count=1; count&lt=10; count++) {
  if (count == 6)
    break;
  console.log(“count: “ + count);
}

This example shows a for loop that counts from 1 to 10 and prints the number at each iteration of the loop. An if statement inside the for loop is used to test if the value in the count variable is equal to 6. If count equals 6, the break statement is executed and the script exits the for loop. As used in this simple example, the script will count from 1 to 6, then stop. It exits the for loop before it can count up to 10.

Note that in real life, break statements are uncommon. They are an interruption of the expected control flow, and make it harder to understand what is happening. They also are not often required. You’d never write a program like the one in the above example—you’d just use a loop that counted to 6. But there are times when a break statement is just the thing; sometimes as a way to get something working before refactoring.

Also note that a break statement will exit the nearest enclosing block. So if you have nested loops, break jumps out of the most inner loop.

continue

The continue statement tells JavaScript to skip any instructions that may follow in a for, for…in, or while loop, and proceed with the next iteration. Like break, continue is not very common because it violates the typical code flow. The most common use of the continue statement is to conditionally skip instructions in the loop but not exit the loop (as the break statement does):


for (Count=1; Count&lt=10; Count++) {
    if (Count == 6)
        continue;
    document.write ("<P>Loop: " + Count + "</P>");
}

This example shows a for loop that counts from 1 to 10 and prints the number at each iteration of the loop. An if statement inside the for loop is used to test if the value in the count variable is equal to 6. If count equals 6, the continue statement is executed, and the script skips the document.write instruction on the next line. But the loop doesn’t end. Instead, it continues and prints lines for the remaining numbers. As used in this simple example, the script will count from 1 to 5, skip 6, then print 7 through 10.

switch

The switch statement is an alternative way to conditional branch code flow, similar to if...else. It gives you a more compact way to deal with many options. Here’s a simple example:


const fruit = "apple";

switch (fruit) {
  case "apple":
    console.log("You chose an apple! ");
    break;
  case "banana":
    console.log("You chose a banana! ");
    break;
  default:
    console.log(`You chose something other than an apple or banana: ${fruit}`);
}

Modern JavaScript has a powerful switch statement; it can handle almost any kind of variable you throw at it.

Error conditions: try, catch, finally, throw

In closing our tour of JavaScript statements, let’s look at the error handling statements. Developers use the try, catch, finally, and throw statements together to deal with error conditions:

  • try wraps the code block that follows it into a container. Doing so puts all errors into a catch statement immediately following the code block.
  • catch addresses any errors emerging from the preceding try block.
  • finally ensures a block executes after the preceding try block finishes, whether there is an error in the code or not.
  • throw raises a new error, which will be handled by any try/catch blocks upstream.

Here’s a simple example of these statements in a JavaScript program:


try {
  const age = parseInt(prompt("Enter your age:"));
  if (isNaN(age)) {
    throw new Error("Invalid age entered!");
  }

  if (age < 10) {
    console.log("You are too young to join this website.");
  } else if (age < 65) {
    console.log("Welcome! Enjoy exploring our content.");
  } else {
    console.log("We have special offers for users over 65!");
  }
} catch (error) {
  console.error(`Error: ${error.message}`);
} finally {
  console.log("Thank you for using our website!");
}

Conclusion

Statements are a foundational part of any programming language, and JavaScript has an expressive and well-developed set of them. In this article, you’ve been introduced to the JavaScript statements you are most likely to see and use in your programs. Knowing JavaScript statements and using them effectively is key to mastering almost any programming scenario in JavaScript.