JavaScript Statements and semicolons

JavaScript statements are the basic building blocks of JavaScript code. A statement is a single instruction that the JavaScript engine executes to perform an action, such as declaring a variable, assigning a value, or calling a function. Statements in JavaScript are generally separated by semicolons.

  1. JavaScript Statements: JavaScript statements can include variable declarations, assignments, function calls, loops, conditionals, and other expressions. Here are a few examples of JavaScript statements:
// Declare a variable
var x;

// Assign a value to a variable
x = 10;

// Declare a variable and assign a value
var y = 20;

// Call a function
console.log(x + y);

// Use a conditional statement
if (x > y) {
  console.log("x is greater than y");
} else {
  console.log("x is not greater than y");

Each of these lines represents a separate JavaScript statement. In some cases, a single line may contain multiple statements, such as:

var a = 1, b = 2, c = 3;
  1. Semicolons: Semicolons are used to separate JavaScript statements, making it clear where one statement ends and another begins. Although JavaScript engines can automatically insert semicolons in many cases (a feature known as Automatic Semicolon Insertion or ASI), it is considered best practice to include semicolons explicitly to avoid any potential issues or misunderstandings. Here's an example of JavaScript statements separated by semicolons:
var x = 10;
var y = 20;
var sum = x + y;

In some cases, omitting a semicolon can lead to unexpected behavior or errors. For example:

// This code will produce unexpected results
var a = 10
(function() {
  console.log("Hello, World!");

In this example, JavaScript will insert a semicolon after `10`, but it will not insert one after the function declaration. As a result, the code will throw an error. To fix this, you can add a semicolon explicitly:

var a = 10;
(function() {
  console.log("Hello, World!");

To summarize, JavaScript statements are the individual instructions that make up JavaScript code, and semicolons are used to separate these statements. While JavaScript can automatically insert semicolons in many cases, it is a best practice to include them explicitly to ensure that your code is clear and free of potential issues.

Was this page helpful?