Semicolon in JavaScript
In JavaScript, a semicolon (;) is used to terminate a statement. It is optional in most cases, but it is recommended to use it to avoid unexpected behavior.
Here are some examples of using semicolons in JavaScript:
- Terminate a statement:
let x = 5;
console.log(x);
- Separate multiple statements on the same line:
let x = 5; console.log(x);
- Use it with control structures like if, for, while, etc.:
if (x > 0) {
console.log("x is positive");
}
- Use it with function expressions and declarations:
// Function expression
const add = function(a, b) {
return a + b;
};
// Function declaration
function multiply(a, b) {
return a * b;
}
- Use it with object literals:
const person = {
name: "John",
age: 30,
sayHello: function() {
console.log("Hello");
}
};
In general, it is recommended to use semicolons consistently throughout your code to avoid any unexpected behavior. However, some developers prefer to omit semicolons and rely on automatic semicolon insertion by the JavaScript engine.