JavaScript Operators

Operators

An Operator is a symbol used for a specific task. That task may be related to math or logical operation. Operators work on operands.


var sum = 2 + 3;

Here 2, 3 are operands and + is an operator.

It can be any types like –

  1. Assignment
  2. Arithmetic
  3. Comparison
  4. Logical

Assignment

This operator assigns operands value to a variable. Ex-


var sum = 5;

here = is assignment operator which assign a value of 5 into some variable.

Arithmetic

Following table related to the arithmetic operator. Where


var x = 2;
var y = 4;

Operator Description Example
+ Addition x + y = 6
Addition x + y = 6
% Modulus y % x = 0
/ Division y / x = 2
% Modulus y % x = 0
++ Increases the value of x by 1 ++x = 3
Decreases the value of x by 1 –x = 1

Increment and Decrement operator increases and decreases the value of the variable by 1. It is two type –

Prefix – In prefix operator should be before the variable. Like ++x, –x
Postfix – In postfix operator should be after the variable. Like x++, x–

But the difference between prefix and postfix is –

In the case of the prefix, the variable value is incremented by 1 then, It returns the value. But In case of postfix original value returned first then variable incremented by 1. Ex –


//first example
var x = 2;
console.log(++x); // 3

//second example 
var x = 2;
console.log(x++); // 2
console.log(x); // 3

Comparison operators

It is used in logical statements to determine equality, difference.

== equal to
=== equal value and equal type
!= not equal
!== not equal value or not equal type
> greater than
< less than
>= greater than or equal to
<= less than or equal to
? ternary operator

Logical Operators

It is used with a boolean value. If we used this they return boolean value like true and false.

&& ogical and
|| logical or
! logical not

About the Author: Pankaj Bisht