OPERATORS

Operators

Arithmetic Operators

The arithmetic operators perform addition, subtraction, multiplication, division, exponentiation, and modulus operations.

  1. Addition(+)
  2. Subtraction (-)
  3. Multiplication(*)
  4. Division(/)
  5. Remainder of division (%)
  6. Exponentiation (**)
  7. Increment (++)
  8. Decrement (- -)

Example :

let x = 10;
let y = 4;
console.log(x + y);
//output:14
console.log(x - y);
// output:6
console.log(x * y);
// output:40
console.log(x / y);
// output:2.5
console.log(x % y);
// output:2
console.log(x ** y);
// output:10000
console.log(++x)
//output:11
console.log(--x)
//output:9

Assignment operators

An assignment operator assigns a value to its left operand based on the value of its right operand.

let x = 3;

Comparison Operators

A comparison operator compares its operands and returns a logical value based on whether the comparison is true. The operands can be numerical, string, logical, or object values.

  1. Relational operator
  2. Equality operator
let x = 1;
//Relational
console.log(x > 0) //output:true
console.log(x >= 1) //output:true
console.log(x < 1) //output:false
console.log(x <= 1) //output:true
//Equality
console.log(x === 1) //output:true
console.log(x !== 1) //output:false

Equality Operators

1. Strict equality ( === )

The both value we have on the sides of this operator have the same type and same value
console.log( 1 === 1) //output: true
console.log( '1' === 1) //output: false

2. Lose equality ( == )

The both value we have on the sides of this operator have the same value it won’t check type
console.log( 1 == 1) //output:true
console.log( '1' == 1) //output:true

Ternary operator or conditional operator

The conditional operator is the only JavaScript operatorthat takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.

Syntax

condition ? runs if true : runs if false

Example :

var age = 20;
age >= 18 ? console.log("adult") : console.log("minor"); // Prints: adult

Logical Operators

There are three main logical operators.

AND Operator (&&)

If both conditions are true then it returns true else false.

Example :

var x = 6;
var y = 3;
console.log(x < 10 && y < 1);
// Prints: false

OR Operator (||)

If any one condition is true then it returns true

Example :

var x = 6;
var y = 3;
console.log(x < 10 || y < 1);
// Prints: true

NOT Operator (!)

If a condition is true, then the NOT operator will make it false.

Example :

var x = 6;
var y = 3;
// with out !
console.log(x == y); // Prints
: false
// with !
console.log(!(x == y)); // Prints: true