JavaScript Operators

In JavaScript, operators are used to perform operations on variables and values. Operators allow you to manipulate data and variables in various ways, such as performing arithmetic operations, comparing values, or making decisions based on conditions.

Types of JavaScript Operators:

Arithmetic Operators:

Arithmetic operators are used to perform mathematical calculations on numbers. Here are the basic arithmetic operators:

Example of Arithmetic Operators:

This example demonstrates how to use arithmetic operators in JavaScript.

Example 1


let a = 10;
let b = 5;
            
console.log(a + b);  // Output: 15
console.log(a - b);  // Output: 5
console.log(a * b);  // Output: 50
console.log(a / b);  // Output: 2
console.log(a % b);  // Output: 0                                   
 

Output:

15
5
50
2
0

Assignment Operators:

Assignment operators are used to assign values to variables. The most common assignment operator is the = operator, but there are several others that combine arithmetic and assignment.

Example of Assignment Operators:

This example demonstrates how to use assignment operators in JavaScript.

Example 2


let x = 10;
x += 5; // x = x + 5
console.log(x); // Output: 15
            
x *= 2; // x = x * 2
console.log(x); // Output: 30

Output:

15
30

Comparison Operators:

Comparison operators are used to compare two values. These operators return a boolean value (true or false) depending on the result of the comparison.

Example of Comparison Operators:

This example demonstrates how to use comparison operators in JavaScript.

Example 3


let a = 5;
let b = 10;
            
console.log(a == b);  // Output: false
console.log(a != b);  // Output: true
console.log(a > b);   // Output: false
console.log(a < b);   // Output: true

Output:

false
true
false
true

Logical Operators:

Logical operators are used to perform logical operations on boolean values.

Example of Logical Operators:

This example demonstrates how to use logical operators in JavaScript.

Example 4


let a = true;
let b = false;
            
console.log(a && b); // Output: false
console.log(a || b); // Output: true
console.log(!a);     // Output: false

Output:

false
true
false

Conditional (Ternary) Operator:

The conditional (ternary) operator is a shorthand way of performing conditional checks. It has the following syntax: condition ? expr1 : expr2 If the condition is true, expr1 is executed; otherwise, expr2 is executed.

Example of Conditional (Ternary) Operator:

This example demonstrates the usage of the ternary operator in JavaScript.

Example 5


let age = 18;
let result = (age >= 18) ? "Adult" : "Minor";
console.log(result); // Output: Adult

Output:

Adult