JavaScript Operators
Definition
JavaScript operators are special symbols used to perform operations on variables and
values. They help manipulate data, perform calculations, and make decisions in programs.
Example
let x = 10 + 5; // '+' is an operator
Types of JavaScript Operators
1. Arithmetic Operators
Used to perform mathematical operations.
Operators: + , - , * , / , % , **
let a = 10, b = 3;
a + b // 13
a - b // 7
a * b // 30
a / b // 3.33
a % b // 1
a ** b // 1000
2. Assignment Operators
Used to assign values to variables.
Operators: = , += , -= , *= , /= , %=
let x = 10;
x += 5; // 15
x -= 2; // 13
x *= 2; // 26
x /= 2; // 13
3. Comparison Operators
Used to compare two values and return boolean results (true or false).
Operators: == , === , != , !== , > , < , >= , <=
5 == "5" // true
5 === "5" // false
10 > 5 // true
3 <= 2 // false
4. Logical Operators
Used to combine conditions.
Operators: && , || , !
let a = 10;
(a > 5 && a < 20) // true
(a > 5 || a > 20) // true
!(a > 5) // false
5. Bitwise Operators
Operate on binary representation of numbers.
Operators: & , | , ^ , ~ , << , >>
5 & 1 // 1
5 | 1 // 5
5 ^ 1 // 4
5 << 1 // 10
6. Unary Operators
Operate on a single operand.
Operators: ++ , -- , typeof , + , -
let x = 5;
x++; // 6
x--; // 5
typeof x // number
7. Ternary Operator
Shortcut for if-else condition.
Syntax: condition ? expr1 : expr2
let age = 18;
let result = (age >= 18) ? "Adult" : "Minor";
8. String Operators
Used to concatenate strings.
Operator: +
let a = "Hello";
let b = "World";
a + " " + b // Hello World
9. Type Operators
Used to check data types.
Operators: typeof , instanceof
typeof "Hello" // string
let arr = [];
arr instanceof Array // true
10. Spread and Rest Operators
Used in arrays and functions.
Operator: ...
// Spread
let arr1 = [1,2];
let arr2 = [...arr1, 3,4];
// Rest
function sum(...nums) {
return [Link];
}
Complete JavaScript Program Using Operators
This program demonstrates the use of arithmetic, assignment, comparison, logical,
ternary, string, type, and unary operators together in one example.
// Complete Program Using Operators
let a = 10;
let b = 5;
// Arithmetic Operators
let sum = a + b;
let product = a * b;
// Assignment Operator
a += 2; // a becomes 12
// Comparison Operator
let isGreater = a > b;
// Logical Operator
let checkRange = (a > 5 && a < 20);
// Unary Operator
b++;
// Ternary Operator
let result = (a % 2 === 0) ? "Even" : "Odd";
// String Operator
let message = "Result is: " + result;
// Type Operator
let typeCheck = typeof a;
// Output
[Link]("Sum:", sum);
[Link]("Product:", product);
[Link]("Is a greater than b?", isGreater);
[Link]("Range Check:", checkRange);
[Link](message);
[Link]("Type of a:", typeCheck);