JavaScript Statements: Complete Guide with Examples

Learn JavaScript Statements with easy explanations and examples. Understand variables, expressions, conditions, loops, functions, return, break, continue, switch, and more.

JavaScript Statements: Complete Guide for Beginners

JavaScript statements are the instructions that tell a JavaScript program what to do. Almost every JavaScript program is made up of statements. A statement can create a variable, calculate a value, display a message, make a decision, repeat an action, define a function, or control the flow of a program.

Understanding statements is one of the first important steps in learning JavaScript. Once you understand how statements work, writing larger programs becomes much easier.

What Are JavaScript Statements?

A JavaScript statement is a complete instruction that the JavaScript engine can execute.

For example:

let name = "Dibya";

This statement creates a variable named name and assigns the value "Dibya" to it.

Another example is:

console.log("Hello, JavaScript!");

This statement tells JavaScript to display a message in the console.

A JavaScript program can contain many statements:

let name = "Dibya";
let age = 25;

console.log(name);
console.log(age);

The JavaScript engine normally executes these statements in order, from top to bottom, unless a control-flow statement changes that behavior.

Basic Structure of a JavaScript Statement

A statement may contain several parts, depending on what it does.

For example:

let age = 25;

Here:

  • let is a keyword.
  • age is the variable name.
  • = is the assignment operator.
  • 25 is the value.
  • ; is the semicolon that terminates the statement.

Not every JavaScript statement contains all of these parts.

For example:

console.log("Hello");

is also a complete statement.

Semicolons in JavaScript

JavaScript uses semicolons (;) to separate statements.

For example:

let x = 10;
let y = 20;
let sum = x + y;

Semicolons are generally optional because JavaScript has a feature called Automatic Semicolon Insertion (ASI).

This is also valid:

let x = 10
let y = 20
console.log(x + y)

However, using semicolons consistently can make code easier to read and can help avoid certain ASI-related problems.

A good practice is to follow one consistent coding style throughout a project.

JavaScript Statements vs Expressions

These two concepts are closely related but are not exactly the same.

An expression produces or evaluates to a value.

10 + 20

The expression evaluates to:

30

A statement performs an action or controls program execution.

let result = 10 + 20;

The right side contains an expression, while the complete line is a declaration statement.

Another example:

console.log(10 + 20);

The argument 10 + 20 is an expression, while the complete instruction is an expression statement.

Understanding the difference between expressions and statements becomes particularly useful when working with functions, conditions, loops, and modern JavaScript syntax.

Common Types of JavaScript Statements

JavaScript has many types of statements. Some of the most commonly used are:

  • Variable declaration statements
  • Expression statements
  • Conditional statements
  • Loop statements
  • Function declarations
  • Block statements
  • Return statements
  • Break statements
  • Continue statements
  • Switch statements
  • Exception-handling statements
  • Debugger statements
  • Import and export declarations
  • Class declarations

Let’s look at the important ones in detail.

Variable Declaration Statements

Variable declaration statements create variables that can store values.

JavaScript provides three main ways to declare variables:

var name = "Dibya";
let age = 25;
const country = "India";

let

let creates a block-scoped variable.

let score = 90;
score = 95;

The value can be changed later.

const

const creates a block-scoped binding that cannot be reassigned.

const pi = 3.14159;

This is not allowed:

const pi = 3.14159;
pi = 3.14;

var

var is the older way to declare variables.

var city = "Bhubaneswar";

Modern JavaScript generally prefers let and const because they have clearer block-scoping behavior.

Expression Statements

An expression can be used as a statement when its result is used for an action or side effect.

For example:

console.log("Welcome");

Another example:

x++;

And:

name = "Rahul";

These are expression statements.

Assignment Statements

An assignment statement assigns a value to a variable.

let age;
age = 25;

JavaScript also supports compound assignment operators:

let score = 10;

score += 5;
score -= 2;
score *= 2;
score /= 2;

For example:

score += 5;

is equivalent to:

score = score + 5;

Conditional Statements

Conditional statements allow JavaScript to make decisions.

The most common conditional statement is if.

let age = 20;

if (age >= 18) {
    console.log("You are an adult.");
}

The code inside the block runs only when the condition is true.

if...else

let age = 16;

if (age >= 18) {
    console.log("You can vote.");
} else {
    console.log("You cannot vote yet.");
}

if...else if...else

You can test multiple conditions:

let marks = 75;

if (marks >= 90) {
    console.log("Excellent");
} else if (marks >= 60) {
    console.log("Good");
} else {
    console.log("Needs improvement");
}

The switch Statement

The switch statement is useful when one value needs to be compared with several possible cases.

let day = 2;

switch (day) {
    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    case 3:
        console.log("Wednesday");
        break;

    default:
        console.log("Invalid day");
}

The break statement prevents execution from continuing into the next case.

Loop Statements

Loops allow JavaScript to execute a block of code repeatedly.

They are useful when you need to process lists, generate numbers, search through data, or perform repetitive tasks.

Common JavaScript loops include:

  • for
  • while
  • do...while
  • for...of
  • for...in

The for Statement

A for loop is commonly used when you know how many times an operation should run.

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

The output is:

1
2
3
4
5

The for loop has three main parts:

for (initialization; condition; update) {
    // code
}

The while Statement

A while loop runs as long as its condition remains true.

let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}

Always make sure the condition eventually becomes false. Otherwise, you may accidentally create an infinite loop.

The do...while Statement

A do...while loop executes its body at least once before checking the condition.

let i = 1;

do {
    console.log(i);
    i++;
} while (i <= 5);

This is different from while because the code inside do executes before the condition is tested.

The for...of Statement

for...of is commonly used to iterate over iterable values such as arrays and strings.

const fruits = ["Apple", "Mango", "Banana"];

for (const fruit of fruits) {
    console.log(fruit);
}

It gives you the values directly.

The for...in Statement

for...in is generally used to iterate over enumerable property keys of an object.

const person = {
    name: "Dibya",
    age: 25
};

for (const key in person) {
    console.log(key, person[key]);
}

It produces the property names, such as name and age.

For arrays, for...of is usually more appropriate when you want the actual array values.

Block Statements

A block statement groups multiple statements inside curly braces {}.

{
    let name = "Dibya";
    console.log(name);
}

Blocks are especially common with if, loops, functions, and other control structures.

For example:

if (true) {
    console.log("Statement one");
    console.log("Statement two");
}

The two console.log() statements belong to the same block.

Blocks also create a scope for let and const.

Function Declaration Statements

A function declaration defines a reusable block of code.

function greet() {
    console.log("Hello!");
}

The function can then be called:

greet();

Functions help prevent repetitive code and make programs easier to organize.

A function can also accept parameters:

function greet(name) {
    console.log("Hello, " + name);
}

greet("Dibya");

Return Statements

The return statement sends a value back from a function.

function add(a, b) {
    return a + b;
}

const result = add(10, 20);

console.log(result);

The result is:

30

A return statement also immediately ends the execution of the current function.

function checkAge(age) {
    if (age < 18) {
        return "Not eligible";
    }

    return "Eligible";
}

break Statement

The break statement immediately terminates a loop or switch statement.

for (let i = 1; i <= 10; i++) {
    if (i === 5) {
        break;
    }

    console.log(i);
}

The loop stops when i reaches 5.

continue Statement

The continue statement skips the current iteration of a loop and moves to the next iteration.

for (let i = 1; i <= 5; i++) {
    if (i === 3) {
        continue;
    }

    console.log(i);
}

The output is:

1
2
4
5

The number 3 is skipped.

Labeled Statements

JavaScript supports labels that can be used with statements, particularly for controlling nested loops.

Example:

outerLoop:
for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (i === 1 && j === 1) {
            break outerLoop;
        }

        console.log(i, j);
    }
}

Labels are valid JavaScript, but they are relatively uncommon. In many cases, restructuring the code can make the logic easier to understand.

try...catch Statements

JavaScript provides exception-handling statements for dealing with errors.

try {
    riskyOperation();
} catch (error) {
    console.log("An error occurred:", error);
}

If an exception occurs inside the try block, JavaScript transfers control to the catch block.

finally Statement

The finally block runs after try and catch, whether or not an error occurs.

try {
    console.log("Trying...");
} catch (error) {
    console.log("Error:", error);
} finally {
    console.log("Finished.");
}

This is useful when cleanup must happen regardless of whether an operation succeeds.

throw Statement

The throw statement allows you to create an exception intentionally.

function divide(a, b) {
    if (b === 0) {
        throw new Error("Cannot divide by zero");
    }

    return a / b;
}

The error can then be handled with try...catch.

try {
    console.log(divide(10, 0));
} catch (error) {
    console.log(error.message);
}

debugger Statement

The debugger statement can pause JavaScript execution when developer tools are available.

function calculate() {
    let x = 10;
    debugger;
    return x * 2;
}

When debugging is enabled, execution can pause at the debugger statement so you can inspect variables and program state.

It is mainly a development and debugging feature.

Empty Statement

JavaScript also allows an empty statement.

It consists of a single semicolon:

;

Although valid, it usually has no useful effect and should not be added unnecessarily.

An empty statement can occasionally be useful in special situations where JavaScript syntax requires a statement but you intentionally want no action.

JavaScript Comments Are Not Statements

Comments are used to explain code to developers. They are ignored by the JavaScript engine.

A single-line comment starts with //:

// Store the user's name
let name = "Dibya";

A multiline comment uses /* and */:

/*
This code calculates
the total price.
*/
let total = 500;

Comments are not executed as JavaScript statements.

Statement Blocks and Scope

JavaScript uses curly braces to create blocks.

Consider:

{
    let message = "Hello";
    console.log(message);
}

The message variable exists only inside that block.

For example:

{
    let message = "Hello";
}

console.log(message);

This causes an error because message is not available outside its block.

The same concept applies to const.

{
    const value = 100;
}

console.log(value);

var behaves differently because it is function-scoped rather than block-scoped.

Statement Execution Order

Normally, JavaScript executes statements from top to bottom.

console.log("First");
console.log("Second");
console.log("Third");

The output is:

First
Second
Third

However, conditions, loops, functions, exceptions, asynchronous operations, and other language features can change when and whether particular statements execute.

For example:

let age = 20;

if (age >= 18) {
    console.log("Adult");
}

console.log("Finished");

The first statement creates the variable, the if statement checks the condition, and the final statement executes afterward.

Statements Inside Other Statements

JavaScript statements can be nested.

For example:

for (let i = 1; i <= 5; i++) {
    if (i % 2 === 0) {
        console.log(i);
    }
}

Here:

  • The for statement contains a block.
  • The block contains an if statement.
  • The if block contains an expression statement.

Nested statements are very common in real JavaScript applications.

JavaScript Statement Example

Here is a small program that combines several types of statements:

const numbers = [10, 20, 30, 40, 50];

let total = 0;

for (const number of numbers) {
    if (number > 20) {
        total += number;
    }
}

console.log("Total:", total);

This example contains:

  1. A const declaration.
  2. A let declaration.
  3. A for...of loop.
  4. An if conditional.
  5. An assignment expression statement.
  6. A function call through console.log().

The program adds only numbers greater than 20.

Multiple Statements on One Line

JavaScript allows multiple statements on one line when they are properly separated.

let x = 10; let y = 20; console.log(x + y);

This works, but it is generally harder to read.

A better style is:

let x = 10;
let y = 20;

console.log(x + y);

Readable code is easier to maintain, debug, and review.

Statement Termination and Automatic Semicolon Insertion

JavaScript’s Automatic Semicolon Insertion can insert semicolons in certain situations.

For example:

let name = "Dibya"
let age = 25

is interpreted effectively as separate statements.

However, ASI does not mean that semicolons can always be ignored safely.

One well-known example involves return:

function getValue() {
    return
    {
        value: 10
    };
}

JavaScript treats the return as ending before the object, so the function returns undefined.

Writing it like this avoids the problem:

function getValue() {
    return {
        value: 10
    };
}

This is one reason developers should understand statement termination rather than relying blindly on ASI.

JavaScript Statements and Whitespace

JavaScript generally ignores extra spaces, tabs, and line breaks where they do not affect syntax.

These are equivalent:

let x = 10;

and:

let x     =     10;

However, good formatting is important for human readability.

A clean coding style makes statements easier to understand.

Statements in Strict Mode

JavaScript can run in strict mode using:

"use strict";

For example:

"use strict";

let name = "Dibya";
console.log(name);

Strict mode changes certain JavaScript behaviors and helps identify some common programming mistakes.

Modern JavaScript modules are automatically in strict mode.

Statements in JavaScript Modules

Modern JavaScript supports modules using import and export.

For example:

export function add(a, b) {
    return a + b;
}

Another file can import the function:

import { add } from "./math.js";

console.log(add(10, 20));

Modules make it possible to divide large applications into smaller, reusable files.

Class Declarations

JavaScript also supports class declarations.

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

    greet() {
        console.log(`Hello, ${this.name}`);
    }
}

A class declaration creates a class that can be used to create objects.

const person = new Person("Dibya");

person.greet();

import and export Declarations

JavaScript modules use import and export to share functionality between files.

Example:

export const siteName = "Example";

Then:

import { siteName } from "./config.js";

console.log(siteName);

These declarations are especially important in modern web development.

Why JavaScript Statements Are Important

Statements are the building blocks of JavaScript programs. They allow developers to:

  • Store information.
  • Perform calculations.
  • Make decisions.
  • Repeat operations.
  • Create reusable functions.
  • Handle errors.
  • Control execution.
  • Work with objects and arrays.
  • Build classes.
  • Import and export modules.
  • Interact with web pages.
  • Respond to user actions.
  • Build complex applications.

Without statements, JavaScript would not be able to perform meaningful tasks.

Common Mistakes With JavaScript Statements

Forgetting Braces

Although some statements allow a single statement without braces:

if (age >= 18)
    console.log("Adult");

using braces is often clearer:

if (age >= 18) {
    console.log("Adult");
}

Braces become especially important when the code grows.

Creating Infinite Loops

This loop never changes i:

let i = 1;

while (i <= 5) {
    console.log(i);
}

Because i remains 1, the condition never becomes false.

A correct version is:

let i = 1;

while (i <= 5) {
    console.log(i);
    i++;
}

Misusing = and ===

Assignment:

x = 10;

Strict equality comparison:

x === 10

They have completely different purposes.

Using for...in for Array Values

Consider:

const numbers = [10, 20, 30];

for (const value of numbers) {
    console.log(value);
}

This is generally clearer when you want array values.

for...in is primarily intended for enumerable property keys.

Unnecessary Semicolons

Although semicolons are useful, adding random empty statements can make code confusing:

let x = 10;;;

A cleaner version is:

let x = 10;

Best Practices for Writing JavaScript Statements

Good JavaScript code is not only about making statements work. It should also be readable and maintainable.

Use Meaningful Variable Names

Prefer:

let totalPrice = 500;

over:

let x = 500;

when the value represents a total price.

Prefer const When Reassignment Is Not Needed

For example:

const username = "Dibya";

Use let when the variable needs to be reassigned:

let counter = 0;
counter++;

Keep Statements Simple

Instead of putting too much logic into one statement, separate complex operations into understandable steps.

Use Consistent Formatting

For example:

const price = 100;
const quantity = 3;
const total = price * quantity;

console.log(total);

This is easier to read than placing everything on one line.

Use Strict Equality When Appropriate

Prefer:

if (age === 18) {
    console.log("Exactly 18");
}

when you want both value and type to match.

Avoid Deeply Nested Logic

Excessive nesting can make statements difficult to understand.

When logic becomes complicated, consider using functions or early returns.

JavaScript Statements in Web Development

JavaScript statements are used throughout websites and web applications.

For example, a button can trigger a function:

function showMessage() {
    console.log("Button clicked");
}

An event listener can call that function:

document
    .querySelector("#myButton")
    .addEventListener("click", showMessage);

JavaScript statements can also change HTML:

document.querySelector("#title").textContent = "Welcome!";

They can modify CSS classes:

document.querySelector("#menu").classList.add("active");

They can validate forms:

if (username.trim() === "") {
    console.log("Username is required.");
}

This is how JavaScript turns a static webpage into an interactive application.

A Practical Example

The following example demonstrates several JavaScript statements together:

const productName = "Laptop";
const price = 50000;
const quantity = 2;

let total = price * quantity;

if (quantity > 0) {
    console.log("Product:", productName);
    console.log("Total:", total);
} else {
    console.log("Invalid quantity");
}

Here, the program:

  1. Declares constants.
  2. Performs a calculation.
  3. Stores the result in a variable.
  4. Checks a condition.
  5. Executes different statements based on that condition.
  6. Displays information in the console.

Frequently Asked Questions About JavaScript Statements

What is a JavaScript statement?

A JavaScript statement is an instruction that the JavaScript engine can execute. Examples include variable declarations, conditions, loops, function declarations, and return statements.

Is every JavaScript line a statement?

No. A line can contain part of a statement, multiple statements, or an expression. JavaScript syntax is based on language constructs rather than simply physical lines.

Are semicolons mandatory in JavaScript?

No. JavaScript has Automatic Semicolon Insertion, so semicolons can often be omitted. However, using a consistent semicolon style can improve clarity and prevent some potential problems.

What is the difference between a statement and an expression?

An expression produces a value, while a statement generally performs an action or controls program execution. An expression can also be used as an expression statement.

What is the most common JavaScript statement?

There is no single most important statement. Variable declarations, expression statements, conditional statements, loops, and function declarations are all widely used.

What does the if statement do?

The if statement executes a block of code when a specified condition evaluates to true.

What does the break statement do?

break immediately exits a loop or switch statement.

What does the continue statement do?

continue skips the remaining part of the current loop iteration and proceeds to the next iteration.

What does the return statement do?

return ends a function and can provide a value back to the code that called the function.

Can JavaScript statements be nested?

Yes. Statements such as if, loops, and try blocks can contain other statements.

What is Automatic Semicolon Insertion?

Automatic Semicolon Insertion is a JavaScript parsing behavior in which the language can insert semicolons at certain locations when they are omitted from source code.

Which is better, let or var?

For modern JavaScript, let and const are generally preferred over var because their block-scoping behavior is easier to reason about.

Final Thoughts

JavaScript statements are the basic instructions that make programs work. They allow JavaScript to store data, calculate values, make decisions, repeat operations, create functions, handle errors, and control the flow of execution.

For beginners, the most important statements to learn first are let, const, if, else, switch, for, while, for...of, function, return, break, and continue.

Once these become familiar, you can combine them to build increasingly complex programs. The key is not simply memorizing every statement. Instead, understand what each statement does, when to use it, and how it affects the flow of your program. That understanding forms a strong foundation for learning modern JavaScript, web development, frameworks, and application programming.

Scroll to Top