In JavaScript, operators are symbols that perform operations on operands, such as variables, values, or expressions. JavaScript supports various types of operators for different purposes, such as arithmetic, comparison, logical operations, assignment, and more. Let's explore some of the commonly used operators:
Arithmetic operators are used to perform arithmetic operations on numerical values.
let sum = 5 + 3; // Result: 8
let difference = 10 - 5; // Result: 5
let product = 3 * 4; // Result: 12
let quotient = 12 / 3; // Result: 4
let remainder = 10 % 3; // Result: 1
Comparison operators are used to compare two values and return a Boolean result ( true or false ).
console.log(5 == 5); // Result: true
console.log(5 != 3); // Result: true
console.log(5 === "5"); // Result: false
console.log(5 !== "5"); // Result: true
Logical operators are used to combine or manipulate Boolean values.
console.log(true && true); // Result: true
console.log(true && false); // Result: false
console.log(true || false); // Result: true
console.log(false || false); // Result: false
console.log(!true); // Result: false
console.log(!false); // Result: true
Assignment operators are used to assign values to variables.
let x = 10;
let y = 5;
y += 3; // Equivalent to: y = y + 3; Result: 8
Unary operators are used on a single operand.
let num = +"10"; // Result: 10
Example Usage:
Here's an example demonstrating the use of different operators in JavaScript:
let a = 10;
let b = 5;
// Arithmetic operators
let sum = a + b; // Result: 15
let difference = a - b; // Result: 5
let product = a * b; // Result: 50
let quotient = a / b; // Result: 2
let remainder = a % b; // Result: 0
// Comparison operators
console.log(a > b); // Result: true
console.log(a === b); // Result: false
// Logical operators
let isTrue = true;
let isFalse = false;
console.log(isTrue && isFalse); // Result: false
console.log(isTrue || isFalse); // Result: true
console.log(!isTrue); // Result: false
// Assignment operators
let c = 20;
c += 5; // Equivalent to: c = c + 5; Result: 25
// Unary operators
let num = -10; // Unary minus
console.log(num); // Result: -10
let count = 0;
count++; // Increment
console.log(count); // Result: 1
count--; // Decrement
console.log(count); // Result: 0
JavaScript operators are essential for performing various operations in your code, such as calculations, comparisons, logical evaluations, and more. Understanding how to use these operators and their behavior is fundamental for writing functional and efficient JavaScript programs.