When should I use a semicolon after curly braces in JavaScript?

In JavaScript, semicolons are optional in many cases due to Automatic Semicolon Insertion (ASI). However, understanding when to use semicolons after curly braces is crucial for writing clean, predictable code.

When Semicolons Are Required After Curly Braces

Use semicolons after curly braces when they end a statement, not a declaration. Here are the key cases:

Function Expressions

Function expressions are statements that need semicolons:

<script>
// Function expression - needs semicolon
var greet = function() {
    alert("Hello World!");
};

// Arrow function expression - needs semicolon  
const sayHello = () => {
    console.log("Hello!");
};

console.log("Function expressions defined");
</script>

Object Literals

Object literal assignments need semicolons:

<script>
var person = {
    name: "John",
    age: 30
};

var config = {
    apiUrl: "https://api.example.com",
    timeout: 5000
};

console.log("Objects created:", person.name, config.apiUrl);
</script>

When Semicolons Are NOT Needed

Do not use semicolons after curly braces for declarations:

Function Declarations

<script>
// Function declaration - no semicolon
function sayGoodbye() {
    alert("Goodbye!");
}

// Class declaration - no semicolon
class Calculator {
    add(a, b) {
        return a + b;
    }
}

console.log("Declarations complete");
</script>

Control Structures

// If statements, loops, try-catch - no semicolons
if (true) {
    console.log("No semicolon after if block");
}

for (let i = 0; i 

No semicolon after if block
Loop iteration: 0
Loop iteration: 1
Loop iteration: 2
Try block

Comparison Table

Code Type Semicolon After {} Example
Function Expression Yes var f = function() {};
Object Literal Yes var obj = {};
Function Declaration No function f() {}
Class Declaration No class C {}
Control Structures No if (true) {}

Key Rule

The simple rule is: if you can assign the curly brace construct to a variable, it probably needs a semicolon. If it's a declaration or control structure, it doesn't.

Conclusion

Use semicolons after curly braces when they end statements (function expressions, object literals), but not after declarations (function declarations, classes) or control structures. This distinction helps maintain consistent, readable JavaScript code.

Updated on: 2026-03-15T21:13:59+05:30

460 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements