What is operator?
JavaScript operators are symbols or keywords used to perform operations on values and variables. Operators are special symbols used to calculate, compare, assign, or check values.
Arithmetic Operators
Arithmetic operators perform arithmetic on numbers (literals or variables).
Operator
- + Addition
- - Subtraction
- * Multiplication
- / Division
- % Modulus (Remainder)
let sum = 5 + 3; // Addition
let diff = 10 - 2; // Subtraction
let p = 4 * 2; // Multiplication
let q = 8 / 2; // Division
let a = 8 % 2; // Modulus
console.log(sum, diff, p, q, a);
Output:
8
8
8
4
0
Assignment Operator
Assignment operators assign values to variables.
let x = 10;
x += 5; // 15
x -= 3; // 12
x *= 2; // 24
x /= 4; // 6
x %= 5; // 1
Comparison Operators
Comparison operators are used to compare two values. Comparison operators always return true or false.
5 == "5" // true (loose equality)
5 === "5" // false (strict equality)
5 != "5" // false
5 !== "5" // true
5 > 3 // true
5 < 3 // false
5 >= 5 // true
5 <= 4 // false
Logical Operators
Logical operators are mainly used to perform the logical operations that determine the equality or difference between the values.
let a = true, b = false;
console.log(a && b); // Logical AND
console.log(a || b); // Logical OR
&& returns true if both operands are true.
|| returns true if at least one operand is true.
! negates the boolean value.
Increment Operator (++)
The increment operator increases the value of a variable by 1.
type
- - Pre-Increment (++a)
- - Post-Increment (a++)
1. Pre-Increment (++a)
The value is increased first, then used in the expression.
let a = 5;
console.log(++a); // 6
console.log(a); // 6
2. Post-Increment (a++)
The current value is used first, then increased by 1.
let a = 5;
console.log(a++); // 5
console.log(a); // 6
Decrement (--) Operators
The decrement operator decreases the value of a variable by 1.
type
- Pre-Decrement (--a)
- Post-Decrement (a--)
1. Pre-Decrement (--a)
The value is decreased first, then used in the expression.
let a = 5;
console.log(--a); // 4
console.log(a); // 4
2.Post-Decrement (a--)
The current value is used first, then decreased by 1.
let a = 5;
console.log(a--); // 5
console.log(a); // 4
Top comments (0)