Operators are special symbols that perform operations on operands (values and variables). They are used to manipulate data and perform calculations.
Commonly used operators in JavaScript include:
These operators are used to perform mathematical calculations.
let a = 10;
let b = 5;
let sum = a + b; // 15
let difference = a - b; // 5
let product = a * b; // 50
let quotient = a / b; // 2
let remainder = a % b; // 0
a++; // 11
b--; // 4
These operators are used to assign values to variables.
let x = 10;
x += 5; // 15
x -= 3; // 12
x *= 2; // 24
x /= 4; // 6
x %= 4; // 2
These operators are used to compare two values and return a boolean result.
let p = 10;
let q = '10';
console.log(p == q); // true (value comparison)
console.log(p === q); // false (value and type comparison)
console.log(p != q); // false
console.log(p !== q); // true
console.log(p > 5); // true
console.log(p < 15); // true
console.log(p >= 10); // true
console.log(p <= 10); // true
These operators are used to combine multiple boolean expressions.
let isAdult = true;
let hasID = false;
console.log(isAdult && hasID); // false
console.log(isAdult || hasID); // true
console.log(!isAdult); // false
These operators are used to manipulate strings.
let firstName = "Ayush";
let lastName = "Narware";
let fullName = firstName + " " + lastName; // "Ayush Narware"
firstName += " Gyan"; // "Ayush Smith"
This operator is a shorthand for an if-else statement.
let age = 18;
let canVote = (age >= 18) ? "Yes" : "No"; // "Yes"
These operators are used to check the type of a variable or object.
let num = 42;
console.log(typeof num); // "number"
let str = "Hello";
console.log(typeof str); // "string"
let arr = [1, 2, 3];
console.log(arr instanceof Array); // true
Understanding and using operators effectively is crucial for performing various operations in JavaScript programming.
For more details, you can refer to the MDN Web Docs on Expressions and Operators.