Operators in JavaScript

JavaScript defines operators for arithmetic, comparisons, Boolean logic, assignment, and bit manipulation, along with some miscellaneous operators, including the ternary conditional operator.

JavaScript offers a variety of operators to perform different operations such as arithmetic, comparisons, logical operations, assignment, and bit manipulation. Let’s go through these types with examples:

  1. Arithmetic Operators: These are used to perform mathematical operations:
1
2
3
4
5
6
7
let a = 10, b = 5;

console.log(a + b); // Addition, outputs: 15
console.log(a - b); // Subtraction, outputs: 5
console.log(a * b); // Multiplication, outputs: 50
console.log(a / b); // Division, outputs: 2
console.log(a % b); // Modulus (Remainder), outputs: 0
  1. Comparison Operators: These are used to compare two values:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
let a = 10, b = 5;

console.log(a == b);  // Equal to, outputs: false
console.log(a != b);  // Not equal to, outputs: true
console.log(a === b); // Equal value and equal type, outputs: false
console.log(a !== b); // Not equal value or not equal type, outputs: true
console.log(a > b);   // Greater than, outputs: true
console.log(a < b);   // Less than, outputs: false
console.log(a >= b);  // Greater than or equal to, outputs: true
console.log(a <= b);  // Less than or equal to, outputs: false
  1. Boolean Logic Operators: These are used to perform logical operations:
1
2
3
4
5
let a = true, b = false;

console.log(a && b); // Logical AND, outputs: false
console.log(a || b); // Logical OR, outputs: true
console.log(!a);     // Logical NOT, outputs: false
  1. Assignment Operators: These are used to assign values to variables:
1
2
3
4
5
6
let a = 10;     // Assignment, a becomes 10
a += 5;         // Addition assignment, a becomes 15
a -= 5;         // Subtraction assignment, a becomes 10
a *= 5;         // Multiplication assignment, a becomes 50
a /= 5;         // Division assignment, a becomes 10
a %= 3;         // Modulus assignment, a becomes 1
  1. Bit Manipulation Operators: These operators work on 32 bit numbers and perform bit-level operations:
1
2
3
4
5
6
7
8
9
let a = 5; // Binary: 0101
let b = 3; // Binary: 0011

console.log(a & b);  // Bitwise AND, outputs: 1 (Binary: 0001)
console.log(a | b);  // Bitwise OR, outputs: 7 (Binary: 0111)
console.log(a ^ b);  // Bitwise XOR, outputs: 6 (Binary: 0110)
console.log(~a);     // Bitwise NOT, outputs: -6 (Binary: 1010)
console.log(a << 1); // Left shift, outputs: 10 (Binary: 1010)
console.log(a >> 1); // Right shift, outputs: 2 (Binary: 0010)
  1. Miscellaneous Operators: These include the ternary operator, typeof operator, etc:
1
2
3
4
let a = 10, b = 5;

console.log(a > b ? 'a is greater' : 'b is greater'); // Ternary operator, outputs: "a is greater"
console.log(typeof a); // typeof operator, outputs: "number"

Each operator serves different purposes and helps