Operators are the backbone of any programming language, enabling developers to perform various computations and logical operations. In JavaScript, operators are categorized into several types, each serving a unique purpose. This blog post delves into the most essential operators: Arithmetic Operators, Comparison Operators, Logical Operators, Assignment Operators, the Ternary Operator, and Spread and Rest Operators.
Arithmetic operators are used to perform mathematical calculations. JavaScript provides a comprehensive set of arithmetic operators for basic and advanced mathematical operations.
Addition (+): Adds two numbers.
let sum = 5 + 3; // sum is 8
Subtraction (-): Subtracts one number from another.
let difference = 10 - 4; // difference is 6
Multiplication (*): Multiplies two numbers
let product = 4 * 7; // product is 28
Division (/): Divides one number by another.
let quotient = 20 / 4; // quotient is 5
Modulus (%): Returns the remainder of a division.
let remainder = 15 % 4; // remainder is 3
Exponentiation (*): Raises a number to the power of another number.
let power = 2 ** 3; // power is 8
Increment (++): Increases a variable's value by one.
let counter = 0;
counter++; // counter is now 1
Decrement (-): Decreases a variable's value by one.
let counter = 10;
counter--; // counter is now 9
Comparison operators are used to compare two values. They return a boolean value (true or false) based on the comparison.
Equal (==): Checks if two values are equal (with type coercion).
console.log(5 == '5'); // true
Strict Equal (===): Checks if two values are equal (without type coercion).
console.log(5 === '5'); // false
Not Equal (!=): Checks if two values are not equal (with type coercion).
console.log(5 != '5'); // false
Strict Not Equal (!==): Checks if two values are not equal (without type coercion).
console.log(5 !== '5'); // true