JavaScript operators

In JavaScript, operators are symbols used to perform specific operations on values (operands). They allow you to manipulate variables, compare values, and combine conditions.

1. Arithmetic Operators

Arithmetic operators are used to perform mathematical calculations.

Operator

Description

Example

Result

+

Addition

5 + 3

8

-

Subtraction

5 - 3

2

*

Multiplication

5 * 3

15

/

Division

10 / 2

5

%

Modulus (remainder)

10 % 3

1

++

Increment (adds 1)

let x = 5; x++

6

--

Decrement (subtracts 1)

let x = 5; x--

4

**

Exponentiation (power) (ES6)

2 ** 3

8

Example:

let x = 10;
let y = 3;
console.log(x + y);  // 13
console.log(x - y);  // 7
console.log(x * y);  // 30
console.log(x / y);  // 3.333...
console.log(x % y);  // 1

2. Comparison Operators

Comparison operators are used to compare two values. The result will be either true or false.

Operator

Description

Example

Result

==

Equal to

5 == '5'

true

===

Strict equal (checks type & value)

5 === '5'

false

!=

Not equal

5 != '5'

false

!==

Strict not equal

5 !== '5'

true

> 

Greater than

5 > 3

true

< 

Less than

5 < 3

false

>=

Greater than or equal to

5 >= 5

true

<=

Less than or equal to

3 <= 5

true

Example:

let a = 10;
let b = 5;
console.log(a == b);    // false
console.log(a != b);    // true
console.log(a > b);     // true
console.log(a >= 10);   // true
console.log(a === '10');  // false (strict equality checks type)

3. Logical Operators

Logical operators are used to combine multiple conditions or perform logical operations.

Operator

Description

Example

Result

&&

Logical AND (true if both are true)

(5 > 3 && 10 > 5)

true

`

`

Logical OR (true if at least one is true)

!

Logical NOT (inverts boolean value)

!(5 > 3)

false

Example:

let age = 20;
let isStudent = true;
 
console.log(age > 18 && isStudent);  // true
console.log(age > 18 || isStudent);  // true
console.log(!(age > 18));            // false (inverts true to false)

Combining Comparison and Logical Operators:

You can combine comparison operators with logical operators to form more complex conditions.

Example:

let num = 10;
let isEven = num % 2 === 0;
let inRange = num > 5 && num < 15;
 
console.log(isEven && inRange);  // true
console.log(isEven || num > 15); // true

Summary:

  • Arithmetic operators perform mathematical operations.
  • Comparison operators compare values and return true or false.
  • Logical operators combine multiple conditions and help in making decisions based on complex logic.

 

Post a Comment

0 Comments