Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Why does the JavaScript need to start with ";"?
JavaScript uses semicolons (;) to separate statements and avoid potential issues with automatic semicolon insertion (ASI). Starting lines with semicolons is a defensive programming practice.
The Problem Without Semicolons
JavaScript automatically inserts semicolons at line breaks, but this can cause unexpected behavior when lines are concatenated:
// Without defensive semicolon
let result = getValue()
(function() {
console.log("This might not work as expected");
})();
function getValue() {
return "Hello";
}
JavaScript interprets this as calling getValue() with a function as an argument, which causes an error.
Using Defensive Semicolons
Starting with a semicolon prevents the previous line from affecting your code:
let result = getValue()
// Defensive semicolon prevents issues
;(function() {
console.log("This works correctly");
})();
function getValue() {
return "Hello";
}
This works correctly
Common Cases Requiring Defensive Semicolons
Use leading semicolons before:
- Immediately Invoked Function Expressions (IIFEs)
- Array literals at the start of lines
- Template literals
let data = {name: "John"}
// Without semicolon - potential issue
// [1, 2, 3].forEach(console.log)
// With defensive semicolon - safe
;[1, 2, 3].forEach(console.log);
;(function() {
console.log("IIFE with defensive semicolon");
})();
1 0 [ 1, 2, 3 ] 2 1 [ 1, 2, 3 ] 3 2 [ 1, 2, 3 ] IIFE with defensive semicolon
Best Practices
While modern linters and formatters handle most cases, defensive semicolons remain useful when:
- Working with concatenated or minified code
- Writing IIFEs or array operations at line starts
- Ensuring code works regardless of previous statements
Conclusion
Defensive semicolons prevent automatic semicolon insertion issues. Use them before IIFEs and array literals to ensure your code executes correctly regardless of preceding statements.
