Writing Statements In JavaScript

In this short lesson you will learn about statements in JavaScript, the syntax, and how to write them for yourself.

We will cover:

What is a statement?

Within a program, a script consists of a series of individual instructions that the computer can follow. Each of these instructions is known as a statement.

Think of statements as the building blocks of JavaScript programs. They define the tasks that the program should perform.

A useful way to think about statements is that JavaScript is a programming language, and statements are the equivalent of sentences within it.

Learning how to write clear statements not only improves your code, but also the experience of those reading it.

Writing a statement

Here is an example of a very simple statement:

console.log("Hello, Middle Earth!");

In the line above we're calling the log() method on the global console object. When this code is executed, the string 'Hello, Middle Earth!' will be outputted to the console.

You can use statements for all kinds of instructions. Here's another example:

const name = 'Frodo';

This time we're declaring a variable called name and assigning it to the string value of 'Frodo'.

Semicolons

As you may have noticed in the previous examples, a statement in JavaScript is ended with a semi-colon ;.

The semi-colon is actually optional and, in fact, nowadays some people choose to omit them altogether.

However, they help to improve readability, and formatters like Prettier will frequently include them by default.

Whitespace and line breaks

JavaScript ignores extra spaces and line breaks, making your code more flexible to format.

This means that the following two snippets are equivalent:

// Declaring variables on separate lins
const companion = "Samwise";
const enemy = "Gollum";
// Declaring variables on the same line
const companion = "Samwise"; const enemy = "Gollum";

However, most of the time you'll see statements declared on new lines, as it can be much easier to read.

Grouping

You can group multiple statements together using curly braces {} to form a code block:

{
    const num1 = 2;
    const num2 = 4;
    console.log(num1 + num2);
}

Blocks are often used in functions, loops, and conditionals.

Summary

Hopefully you'll agree that statements are pretty straightforward! In this short lesson you've learned what a statement is, how to write one, and how they can be combined together to form programs.

Understanding statements is foundational to learning JavaScript and programming in general. They allow you to communicate with the computer and direct it to perform tasks.