Table of Contents
Javascript Operators
Operators are simply some functions having a arithmatic, logical or bitwise property. To start with, we will to through arithmetic operators first as we know maths.
Arithmatic Operators
| Operator | Property |
|---|---|
| + | Addition |
| – | Substraction |
| * | Multiplication |
| \ | Division |
| % | Mod |
| = | Assignment |
| ++ | Increment |
| — | Decrement |
We are quite familiar with some of the operators but we’ll learn each on in detail.
Addition
var num1 = 10; var num2 = 20; var total = num1+num2; //total = 20
Here, total will hold the value of sum of the numbers.
Substraction
var num1 = 10; var num2 = 20; var total = num1-num2; //total = -10
Here, total will hold the value of difference of the numbers, with sign, (-) in this case.
Multiplication
var num1 = 10; var num2 = 20; var total = num1*num2; //total = 200
Here, total will hold the value of multiplication of the numbers.
Division
var num1 = 10; var num2 = 20; var total = num1/num2; //total = 0.5
Here, total will hold the value of quotient. 0.5 in this case.
Modulus
var num1 = 10; var num2 = 20; var total = num1%num2; //total = 10
Here, total will hold the value of remainder.10 in this case.
Assignment
var num1 = 10; var num2; var num2 = num1; //num2 = num1 = 10
Here, num2 will hold the value of num1. The assignment is done from right to left hand side. Simple Maths, isn’t it.
Increment
var num = 10; var total = num++; //total = 11 var total = num+=4; //total = 11+4 = 15
Increment operator is just like addition, but used when you need to add a numeric value to the variable itself.
Decrement
var num = 10; var total = num--; //total = 9 var total = num-=2; //total = 9-2 = 7
Increment operator is just like substraction, but used when you need to substract a numeric value from the variable.
Note – You can also use increment/decrement with mulitiplication, division and modulus operators as well. Try this in the browser.
String Operators
Unlike arithmatic operators, + is the only operator which is used to concatinate 2 or more strings together.
var first = "Fname"; var last = "Lname"; var name = first + " " + last; //Fname Lname
var first = "Fname"; var name +=" Lname"; //Fname Lname var name = first + " Lname"; //Fname Lname
String and Numbers
In Javascript you can add numbers and strings together and the output will be a string.
var number = 10; var name = 'Name'; var result = number+name; //10name result = name+number; //name10
Comparision Operators
| Operator | Property |
|---|---|
| == | Equal to |
| != | Not Equal to |
| === | Equal to and equal type |
| !== | Equal to not equal type |
| > | Greater than |
| < | Less than |
| >= | Greater than equal to |
| <= | Less than equal to |
Logical Operators
| Operator | Property |
|---|---|
| && | Logical and |
| || | Logical or |
| ! | Logical not |
We will go through these operators in more details in the next section when we will cover conditional statements.