JavaScript and TypeScript course Β· Module 1: JavaScript Basics

Semicolons and Their Optionality

7 min read Β·
In this lesson9

In Jurassic Park, there are safety protocols that must be strictly followed, but there are also those that can sometimes be flexibly interpreted depending on the situation. A similar situation exists in JavaScript with semicolons - sometimes they are absolutely necessary, and other times completely optional.

The Role of Semicolons in JavaScript

Semicolons (;) are used to separate statements in JavaScript. They are like security gates between individual procedures in Jurassic Park - they clearly mark where one operation ends and the next begins.

let velociraptorCount = 3;           // First statement
velociraptorCount = velociraptorCount + 2;  // Second statement
console.log("Number of velociraptors: " + velociraptorCount);  // Third statement

When Are Semicolons Optional?

JavaScript has a mechanism called "Automatic Semicolon Insertion" (ASI). This mechanism allows semicolons to be omitted in many cases, as JavaScript intelligently guesses where they should be.

It's like a situation in Jurassic Park where experienced dinosaur trainers can sometimes skip some steps of the procedure because they know how to behave safely.

// Code without semicolons - ASI will insert them automatically
let trexWeight = 8000
console.log("T-Rex weight: " + trexWeight)

In the above example, JavaScript interprets the code as if it looked like this:

let trexWeight = 8000;
console.log("T-Rex weight: " + trexWeight);

How Does ASI Work?

ASI (Automatic Semicolon Insertion) works according to several rules that are worth understanding.

1. ASI Works at End of Line

JavaScript automatically inserts a semicolon when it encounters a newline character, if it believes the statement should end at that point:

let dinoName = "Velociraptor"  // ASI will insert a semicolon here
let dinoHeight = 0.5           // ASI will insert a semicolon here

2. ASI Ends a Statement After return When a New Line Follows

After the words return, break, continue and throw, JavaScript does not look for the rest of the statement on the next line, it inserts a semicolon right away:

function checkDinosaur() {
    return   // ASI will insert a semicolon here
    {
        species: "T-Rex"
    }
}

Warning! In the above example, ASI will cause the function to return undefined, not the object, as one might expect. To avoid such unexpected results, you should write:

function checkDinosaur() {
    return {
        species: "T-Rex",
        dangerous: true
    };
}

3. ASI Won't Activate if Line Ends with an Operator

If a line ends with an operator (e.g., +, -, *), JavaScript assumes the statement continues on the next line:

let longMessage = "Dinosaurs in Jurassic Park " +
                  "are constantly monitored"  // ASI will not insert a semicolon after the first line

Just as not following procedures in Jurassic Park can lead to unfortunate accidents, relying solely on ASI can cause unexpected errors. Here are several situations where ASI may behave differently than expected:

1. Starting a Line with Parentheses

let a = 5
(function() {
    console.log("This function will be called immediately!")
})()

JavaScript will interpret this as:

let a = 5(function() {
    console.log("This function will be called immediately!")
})();

Which will cause an error because 5 is not a function. The correct notation is:

let a = 5;
(function() {
    console.log("This function will be called immediately!")
})();

2. Starting a Line with [ or + Operators

let dinosaurs = ['T-Rex', 'Velociraptor']
['Triceratops', 'Brachiosaurus'].forEach(function(dino) {
    console.log(dino)
})

JavaScript may interpret this as an attempt to access the dinosaurs array using the index ['Triceratops', 'Brachiosaurus'], which will cause an error. The correct notation:

let dinosaurs = ['T-Rex', 'Velociraptor'];
['Triceratops', 'Brachiosaurus'].forEach(function(dino) {
    console.log(dino)
});

Best Practices

In the JavaScript world, there are two schools of thought regarding semicolons, just as in Jurassic Park there are different approaches to managing dinosaurs:

"Always use semicolons" Approach

This is like following all safety procedures in the park, even if some seem redundant:

  • Always place semicolons at the end of statements
  • Avoid potential ASI pitfalls
  • Code is more readable and predictable
  • Easier to collaborate with other developers
// Code with semicolons
let parkStatus = "Open";
let visitorCount = 1500;

function updateStatus(newStatus) {
    parkStatus = newStatus;
    return parkStatus;
}

updateStatus("Closed for safety reasons");
console.log("Current status: " + parkStatus);

"Rely on ASI" Approach

This is like allowing experienced trainers some freedom in working with dinosaurs:

  • Rely on automatic semicolon insertion
  • Avoid "visual noise" in code
  • Follow style guidelines (e.g., Standard JS)
  • Watch out for potential pitfalls
// Code without semicolons
let parkStatus = "Open"
let visitorCount = 1500

function updateStatus(newStatus) {
    parkStatus = newStatus
    return parkStatus
}

updateStatus("Closed for safety reasons")
console.log("Current status: " + parkStatus)

Rules for Safely Omitting Semicolons

If you decide to omit semicolons, here are some safety rules (like safety protocols in Jurassic Park):

  1. Never start a line with (, [ or / (these are dangerous characters for ASI):
// BAD - potential pitfall:
let greeting = "Welcome to Jurassic Park"
(function() {
    console.log(greeting)
})()

// GOOD - add a semicolon before the IIFE:
let greeting = "Welcome to Jurassic Park";
(function() {
    console.log(greeting)
})()

// OR - use a defensive semicolon:
let greeting = "Welcome to Jurassic Park"
;(function() {
    console.log(greeting)
})()
  1. Be careful with return, break, continue, throw statements at line ends:
// BAD - ASI will insert a semicolon after return:
function getDinosaurData() {
    return
    {
        name: "T-Rex"
    }
}

// GOOD - curly brace on the same line as return:
function getDinosaurData() {
    return {
        name: "T-Rex",
        weight: 8000
    }
}
  1. Be consistent in your approach:

Like in park management - either all procedures are followed, or none. Mixing styles leads to chaos and errors.

Helpful Tools for Managing Semicolons

Just as Jurassic Park uses advanced tools to monitor dinosaurs, in JavaScript we have tools to help manage code:

  1. ESLint - allows enforcing consistent use or non-use of semicolons
// In the .eslintrc.json file:
{
    "rules": {
        "semi": ["error", "always"]  // or "never" for no-semicolon style
    }
}
  1. Prettier - automatically formats code, adding or removing semicolons according to configuration
// In the .prettierrc file:
{
    "semi": true  // or false for no-semicolon style
}

What to Choose?

The choice between using and omitting semicolons in JavaScript is like the decision about management style in Jurassic Park - more formal adherence to procedures or a flexible approach based on experience.

  • Using semicolons is safer, especially for beginners and larger teams
  • Omitting semicolons can work in small teams with clearly defined standards

In professional JavaScript code, the most important thing is consistency - either you use semicolons everywhere, or nowhere. Mixing styles leads to chaos and errors, just as inconsistent adherence to safety protocols in a park full of dinosaurs would lead to catastrophe.

Ultimately, as Dr. Ian Malcolm said in Jurassic Park: "Your programmers were so preoccupied with whether they could skip semicolons, they didn't stop to think if they should."

Summary

  1. Semicolons in JavaScript are used to separate statements
  2. ASI (Automatic Semicolon Insertion) allows omitting semicolons in many situations
  3. There are ASI pitfalls, especially when starting lines with certain characters
  4. Choose one style and apply it consistently throughout all code
  5. Tools like ESLint and Prettier help maintain a consistent style

In the next lesson, we will look at variable declarations in JavaScript, where we'll learn about var, let, and const - different ways of labeling and securing our data, similar to different security levels for different dinosaur species in Jurassic Park.

Code for this lesson: index.js
// Security System - Conditional Statements
// Exercise: Using if, else if, else

// Simple condition
const securityLevel = 3;

if (securityLevel >= 5) {
  console.log("ALARM! Critical level!");
} else if (securityLevel >= 3) {
  console.log("CAUTION! Elevated threat.");
} else {
  console.log("Normal level.");
}

// Comparison operator
const fenceVoltage = 10000;
const requiredVoltage = 8000;

if (fenceVoltage >= requiredVoltage) {
  console.log("Fence: ACTIVE");
} else {
  console.log("Fence: FAILURE!");
}

// Your task:
// 1. Write a condition checking the incubator temperature
// 2. Use else if for different ranges
// 3. Display the appropriate message

// Your code here:

Docs entries used in this lesson

Spotted a mistake in this lesson?

Check yourself

Answer the questions from this lesson. Pick an answer to see right away whether it is correct.

  1. 1. Which character terminates a statement in JavaScript?

  2. 2. Is the semicolon at the end of a statement mandatory in JavaScript?

  3. 3. What does the abbreviation ASI stand for in the context of JavaScript?

  4. 4. What will a function return when return is on a separate line from the returned object? function f() { return { name: 'Rex' } }

Hands-on tasks in the game

  • Code editor

    Write a monitoring system program that displays three messages in the console, e.g. 'Fences: OK', 'Cameras: OK' and 'Power: 98%'. Put each console.log() on its own line and end it with a semicolon. At the top add a multi-line comment describing the program, and above each console.log() a single-line comment explaining it.

  1. QuestionJavaScript Syntax - Semicolon
  2. QuestionSemicolon Optionality in JavaScript
  3. QuestionASI Mechanism
  4. Coding taskPractice: Comments and Formatting
  5. QuestionASI Trap with return

Useful articles