Javascript Operators
Operators in javascript , just like in any other programming language, are symbols used to perform operations on values and variables. These help us with -
simple arithmetic operations , assigning values
logical operations, bit-level operations etc.
Some operators such as arithmetic and bitwise operators, are common across many languages.
Assignment Operators -
these help us assign values to variables
let a = 2;
let b = 4;
add / subtract and assign
+= adds a value to the variable and then assigns the result back to it
Similarly , -= will subtract value from variable and assign result back.
let a = 2;
a += 3; // same as: a = a + 3
console.log(a); // 5
let b = 4;
b -= 1; // same as: b = b - 1
console.log(b); // 3
Arithmetic Operators -
These allow us to perform mathematical operations such as addition, subtraction, multiplication, division, and finding the remainder.
let a = 2;
let b = 4;
console.log(a + b); // 6
console.log(b - a); // 2
console.log(a * b); // 8
console.log(b / a); // 2
console.log(a % b); // 2
Comparison Operators -
as the name suggests , these operators are used in comparison of values and return us with boolean values (true / false)
let a = 2;
let b = 4;
console.log(a == b); // false
console.log(a != b); // true (Not equal)
console.log(a < b); // true
console.log(b > a); // true (Greater than)
! - NOT operator
Strict comparison
=== is the strict equality operator. It compares both the value and the data type.
let a = "1";
let b = 1;
console.log(a == b); // true
console.log(a === b); // false
==converts the string"1"into a number before comparing (type coercion)===does not convert types, so"1"(string) and1(number) are different!==Strict not equal (compares value and type)
Logical Operators -
used to combine or modify boolean expressions, they return either true or false.
JavaScript provides three main logical operators:
&&- AND , Both conditions must be true||- OR , At least one condition must be true!- NOT , Reverses the result
let a = 2;
let b = 4;
let c = 6;
let sum = a + b;
console.log(true && true); // true
console.log(true && false); // false
console.log(true || true); // true
console.log(true || false); // true
The NOT ! operator helps us write a condition in reverse.
It flips the result — true becomes false, and false becomes true.
console.log(!true); // false
console.log(!false); // true
with conditions
let a = 2;
let b = 4;
console.log(!(a > b)); // true
Logical operators are often combined with comparison operators:
console.log(sum != c); // false (6 is equal to 6)
console.log(sum == c && true); // true
console.log(a < b && b < c); // true