How to use JavaScript statements in your programs

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

How to use JavaScript statements
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
}
1 2 Page 1
Page 1 of 2