JavaScript has a variety of operators that allow you to perform different types of operations on data. Here is a detailed guide on the various JavaScript operators along with code examples:
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on numerical values.
Addition (+)
The addition operator is used to add two or more numbers together.
javascriptlet num1 = 5;
let num2 = 10;
let sum = num1 + num2;
console.log(sum); // Output: 15
Subtraction (-)
The subtraction operator is used to subtract one number from another.
javascriptlet num1 = 10;
let num2 = 5;
let difference = num1 - num2;
console.log(difference); // Output: 5
Multiplication (*)
The multiplication operator is used to multiply two or more numbers.
javascriptlet num1 = 5;
let num2 = 10;
let product = num1 * num2;
console.log(product); // Output: 50
Division (/)
The division operator is used to divide one number by another.
javascriptlet num1 = 10;
let num2 = 2;
let quotient = num1 / num2;
console.log(quotient); // Output: 5
Modulus (%)
The modulus operator is used to find the remainder of a division operation.
javascriptlet num1 = 10;
let num2 = 3;
let remainder = num1 % num2;
console.log(remainder); // Output: 1
Assignment Operators
Assignment operators are used to assign values to variables.
Assignment (=)
The assignment operator is used to assign a value to a variable.
javascriptlet num = 5;
console.log(num); // Output: 5
Addition Assignment (+=)
The addition assignment operator is used to add a value to a variable and then assign the result to the variable.
javascriptlet num = 5;
num += 10;
console.log(num); // Output: 15
Subtraction Assignment (-=)
The subtraction assignment operator is used to subtract a value from a variable and then assign the result to the variable.
javascriptlet num = 10;
num -= 5;
console.log(num); // Output: 5
Multiplication Assignment (*=)
The multiplication assignment operator is used to multiply a variable by a value and then assign the result to the variable.
javascriptlet num = 5;
num *= 10;
console.log(num); // Output: 50
Division Assignment (/=)
The division assignment operator is used to divide a variable by a value and then assign the result to the variable.
javascriptlet num = 10;
num /= 2;
console.log(num); // Output: 5
Comparison Operators
Comparison operators are used to compare values.
Equality (==)
The equality operator is used to compare two values for equality.
javascriptlet num1 = 5;
let num2 = 5;
console.log(num1 == num2); // Output: true
Inequality (!=)
The inequality operator is used to compare two values for inequality.
javascriptlet num1 = 5;
let num2 = 10;
console.log(num1 != num2); // Output: true
Strict Equality (===)
The strict equality operator is used to compare two values for equality without type conversion.
javascriptlet num1 = 5;
let num2 = '5';
console.log(num1 === num2); // Output: false