JavaScript Operators
In JavaScript, operators are symbols or keywords used to perform
operations on data values. Operators are categorized based on their
functionality.
1. Arithmetic Operators
Arithmetic operators perform mathematical operations on numbers.
Example:
let a = 10;
let b = 3;
console.log(a + b); // 13
console.log(a % b); // 1
2. Assignment Operators
Assignment operators assign values to variables.
Example:
let x = 10;
x += 5; // x is now 15
x %= 4; // x is now 3
3. Comparison Operators
Comparison operators compare two values and return true or false.
Example:
console.log(5 == '5'); // true (loose equality)
console.log(5 === '5'); // false (strict equality)
console.log(3 > 1); // true
4. Logical Operators
Logical operators combine multiple conditions.
Example:
let age = 20;
console.log(age >= 18 && age < 30); // true
console.log(age > 30 || age < 25); // true
5. Bitwise Operators
Bitwise operators work with binary representations of numbers.
Example:
console.log(5 & 1); // 1
console.log(5 | 1); // 5
console.log(5 << 1); // 10
6. Ternary (Conditional) Operator
The ternary operator (condition ? exprIfTrue : exprIfFalse) is a
shorthand for if-else statements.
Example:
let age = 20;
let status = (age >= 18) ? "Adult" : "Minor";
console.log(status); // "Adult"
7. Type Operators
Type operators include typeof to check the data type of a variable, and
instanceof to verify if an object is an instance of a certain class.
Example:
console.log(typeof "Hello"); // "string"
console.log([] instanceof Array); // true
8. Unary Operators
Unary operators perform an operation on a single operand.
Example:
let num = "5";
console.log(+num); // 5