We use cookies to enhance your experience on the site
CodeWorlds

Semicolons and Their Optionality

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.

1let velociraptorCount = 3;           // First statement
2velociraptorCount = velociraptorCount + 2;  // Second statement
3console.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.

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

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

1let trexWeight = 8000;
2console.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:

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

2. ASI Works Before Closing Curly Brace

JavaScript inserts a semicolon before the closing curly brace of a code block:

1function checkDinosaur() {
2    return   // ASI will insert a semicolon here
3    {
4        species: "T-Rex",
5        dangerous: true
6    }
7}

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:

1function checkDinosaur() {
2    return {
3        species: "T-Rex",
4        dangerous: true
5    };
6}

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:

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

Dangers Related to ASI

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

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

JavaScript will interpret this as:

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

Which will cause an error because

5
is not a function. The correct notation is:

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

2. Starting a Line with
[
or
+
Operators

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

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:

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

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
1// Code with semicolons
2let parkStatus = "Open";
3let visitorCount = 1500;
4
5function updateStatus(newStatus) {
6    parkStatus = newStatus;
7    return parkStatus;
8}
9
10updateStatus("Closed for safety reasons");
11console.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
1// Code without semicolons
2let parkStatus = "Open"
3let visitorCount = 1500
4
5function updateStatus(newStatus) {
6    parkStatus = newStatus
7    return parkStatus
8}
9
10updateStatus("Closed for safety reasons")
11console.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):
1// BAD - potential pitfall:
2let greeting = "Welcome to Jurassic Park"
3(function() {
4    console.log(greeting)
5})()
6
7// GOOD - add a semicolon before the IIFE:
8let greeting = "Welcome to Jurassic Park";
9(function() {
10    console.log(greeting)
11})()
12
13// OR - use a defensive semicolon:
14let greeting = "Welcome to Jurassic Park"
15;(function() {
16    console.log(greeting)
17})()
  1. Be careful with
    return
    ,
    break
    ,
    continue
    ,
    throw
    statements at line ends
    :
1// BAD - ASI will insert a semicolon after return:
2function getDinosaurData() {
3    return
4    {
5        name: "T-Rex",
6        weight: 8000
7    }
8}
9
10// GOOD - curly brace on the same line as return:
11function getDinosaurData() {
12    return {
13        name: "T-Rex",
14        weight: 8000
15    }
16}
  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
1// In the .eslintrc.json file:
2{
3    "rules": {
4        "semi": ["error", "always"]  // or "never" for no-semicolon style
5    }
6}
  1. Prettier - automatically formats code, adding or removing semicolons according to configuration
1// In the .prettierrc file:
2{
3    "semi": true  // or false for no-semicolon style
4}

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.

Go to CodeWorlds