top
upGrad KnowledgeHut SkillFest Sale!

Search

JavaScript Tutorial

Just like any other programming language JavaScript have operators, which works generally on two operands. If there is an expression 5 + 6 then 5 and 6 are operands and + is the operator.JavaScript supports the following types of operators.Arithmetic OperatorsComparison OperatorsLogical (or Relational) OperatorsAssignment OperatorsConditional (or ternary) OperatorsLet’s now look into them in detail.Arithmetic OperatorsJS supports the following arithmetic operators.Addition(+)It adds two operands if they are number. In case one or both operands are string, it will concatenate them.var a = 10; var b = 20; console.log(a + b); //30 var str = "stingValue"; console.log(a + str); //10stingValueSubstraction(-)It subtracts the second operand from the first.var a = 10; var b = 20; console.log(a - b); //-10Multiplication(*)It multiplies both operands.var a = 10; var b = 20; console.log(a * b); //200Division(/)It divides the numerator by the denominator.var a = 20; var b = 10; var c = 3; console.log(a / b); //2 console.log(a / c); //6.666666666666667Modulus(%)It outputs the remainder which we get when we divide the numerator by the denominator.var a = 20; var b = 10; var c = 3; console.log(a / b); //2 console.log(a / c); //6.666666666666667Increment(++)It is one of the few operators which works on only one operand. It is used to increase the integer value by 1.One thing to notice that it behaves a bit different if used before or after the operand as shown in below code. If we use it before the operand, it updates the variable value instantly.Whether as if we use it after the operand, it increases the value in memory but don’t update instantly.var a = 20; var b = 10; console.log(++a); //21 console.log(b++); //10 console.log(a);   //21 console.log(b);   //11Decrement(--)It works like the increment operator. It is used to decrease the integer value by 1.var a = 20; var b = 10; console.log(--a); //19 console.log(b--); //10 console.log(a);   //19 console.log(b);   //9Comparison OperatorsJS supports the following comparison operators.Equal(==)Compares where two operands are equal or not. Returns a Boolean true or false depending on the comparison.One thing to notice is that, if one of the operands to compare is different it converts it to number. Here, variable a and c are different because a is number and c is a string. But the comparison gives true because c is converted to a number before comparison.var a = 20; var b = 10; var c = '20'; console.log(a == b); //false console.log(a == c); //trueStrict Equal(===)Just like the Equal(==) operator, compares where two operands are equal or not. Returns a Boolean true or false depending on the comparison.But it does a strict comparison. It will not do any type of change for operands before comparing. So, the code with 20 === '20' will produce false.var a = 20; var b = 10; var c = '20'; console.log(a === b); //false console.log(a === c); //falseNot Equal(!=)It is the opposite of Equal(==) operator, compares whether two operands are not equal. Returns a Boolean false or true depending on the comparison.But it doesn’t do a strict comparison. It is just like Equal(==) operator, where it converts if the two operands are not of the same data type. So, the code with 20 != '20' will produce false.var a = 20; var b = 10; var c = '20'; console.log(a != b); //true console.log(a != c); //falseStrict Not Equal(!==)Just like Not Equal(!=) operator, compares whether two operands are not equal. Returns a Boolean false or true depending on the comparison.But it does a strict comparison. It will not do any type of change for operands before comparing. So, the code with 20 !== '20' will produce true.var a = 20; var b = 10; var c = '20'; console.log(a !== b); //true console.log(a !== c); //trueGreater than(>)The Greater than(>) operator, checks whether the left operand is greater than the value of the right operand. It returns true if it is or else returns falsevar a = 20; var b = 10; var c = 30; console.log(a > b); //true console.log(a > c); //falseLess than(<)The Less than(>) operator, checks whether the left operand is less than the value of the right operand. It returns true if it is or else returns falsevar a = 20; var b = 10; var c = 30; console.log(a < b); //false console.log(a < c); //trueGreater than or equal to(>=)The Greater than or equal to(>=) operator, checks whether the left operand is greater than or equal to the value of the right operand. It returns true if it is or else returns false.var a = 20; var b = 10; var c = 30; var d = 20; console.log(a >= b); //true console.log(a >= c); //false console.log(a >= d); //trueLess than or equal to(<=)The Less than or equal to(<=) operator, checks whether the left operand is less than or equal to the value of the right operand. It returns true if it is or else returns false.var a = 20; var b = 10; var c = 30; var d = 20; console.log(a <= b); //false console.log(a <= c); //true console.log(a <= d); //trueLogical OperatorsJS supports the following logical operators – Logical AND(&&), Logical OR(||) and Logical Not(!).We will discuss Logical AND(&&) and Logical OR(||) in detail here because Logical Not(!) just reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.Using only the two boolean values true and false, we can generate the truth tables below.It means logical AND(&&) is only true if both operands are true.But even if one operand is true in case of logical OR(||), it will return true.//Logical AND Operation console.log(true && true);  //true console.log(true && false); //false console.log(false && true); //false console.log(false && false);//false //Logical OR Operation console.log(true || true);   //true console.log(true || false);  //true console.log(false || true);  //true console.log(false || false); //falseIn JavaScript, the logical operators can operate on expressions of any type, not just booleans. Also, the logical operators do not always return a boolean valueOne more thing to understand is that JavaScript considers some values as “falsy” and will always return false. Everything else is “truthy” in JavaScript. The following are the six "falsy" values:falseundefinednullNaN0 (both +0 and -0)""Both && and || result in the value of (exactly) one of their operands:A && B returns the value A if A is false; otherwise, it returns B.A || B returns the value A if A is true; otherwise, it returns B.The below code example, shows the same.console.log(0 || 1);  //1 console.log(1 || 2);  //1 console.log(0 && 1);  //0 console.log(1 && 2);  //2JavaScript Bitwise OperatorsJavaScript bitwise operators works on 32-bit numbers. So, the numeric operands are first converted into 32-bit number. The result is converted back to JavaScript number.JS supports the following bitwise operators –Bitwise AND(&)It performs Boolean AND operation on each bit of the operands.Eg -console.log(5 & 1); //1 /* 5 & 1 gets converted into 0101 & 0001, which will result in 0001 and it get converted back to decimal 1 */Bitwise OR(|)It performs Boolean OR operation on each bit of the operands.Eg -console.log(5 | 1); //5 /* 5 | 1 gets converted into 0101 | 0001, which will result in 0101 and it get converted back to decimal 5 */Bitwise NOT(~)It works on one operand only and reverses all of its bits.Eg -console.log(~5); //-6 /* ~5 gets converted into ~00000000000000000000000000000101 , which will result in 11111111111111111111111111111010 and it get converted back to decimal -6 */Bitwise XOR(^)It performs Boolean Exclusive OR operation on each bit of the operands.Eg -console.log(5 ^ 1); //4 /* 5 ^ 1 gets converted into 0101 ^ 0001, which will result in 0100 and it get converted back to decimal 4 */Left Shift(<<)It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros.Eg -console.log(5 << 1); //10 /* 5 << 1 gets converted into 0101 << 1, which will result in 1010 and it get converted back to decimal 10 */Right Shift(>>)It moves all the bits in its first operand to the right by the number of places specified in the second operand. New bits are filled with zeros.Eg -console.log(5 >> 1); //2 /* 5 >> 1 gets converted into 0101 >> 1, which will result in 0010 and it get converted back to decimal 2 */Right Shift with zero(>>>)- h3This operator is just like the >> operator, except that the bits shifted in on the left are always zero.Eg -console.log(5 >>> 1); //2 /* 5 >>> 1 gets converted into 0101 >>> 1, which will result in 0010 and it get converted back to decimal 2 */Assignment OperatorsJS supports the following assignment operators –Simple Assignment(=)Assigns the value of the right-hand operand to the left-hand operand. The right-hand operand can be a simple number, string or a computation statement. The left operand is generally a variable.Eg -var num = 10; var str = "StringValue"; var res = num + str; console.log(res); //10StringValueAdd and Assignment(+=)It adds the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A += B is equivalent to A = A + BEg -var num1 = 10; var num2 = 5; num1 += num2; console.log(num1); //15Subtract and Assignment(-=)It subtracts the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A -= B is equivalent to A = A - BEg -var num1 = 10; var num2 = 5; num1 -= num2; console.log(num1); //5Multiply and Assignment(*=)It multiplies the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A *= B is equivalent to A = A * BEg -var num1 = 10; var num2 = 5; num1 *= num2; console.log(num1); //50Divide and Assignment(/=)It divides the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A /= B is equivalent to A = A / BEg -var num1 = 10; var num2 = 5; num1 /= num2; console.log(num1); //2Modules and Assignment(%=)It divides the right operand to the left operand and assigns the remainder value to the left operand. Actually, it is a short form of notation. The statement A %= B is equivalent toA = A % BEg -var num1 = 10; var num2 = 5; num1 %= num2; console.log(num1); //0Miscellaneous OperatorsJS has the following two miscellaneous operators, which doesn’t fit into any category.Conditional Operator(? :)The conditional operator is quite similar to if…else statement and can be thought of a short-form to it. The conditional operator first evaluates an expression for a true or false value and then executes the first one if the result is true and the second one if the result is false.Eg -var num1 = 10; var num2 = 5; var res = num1 > num2 ? 'num1 is greater' : 'num2 is greater'; console.log(res); //num1 is greatertypeof OperatorThe typeof operator is a very useful unary operator, which can be used to find the data type any variable.  Let consider the example below and we will see the typeof operator returns correctly the data type of the variables.Eg -var num = 10; var str = "I am String"; var num2; var bool = true; var myFunc = function() {}; var myObj = {}; var num3 = null; console.log(typeof num); //number console.log(typeof str); //string console.log(typeof num2); //undefined console.log(typeof bool); //boolean console.log(typeof myFunc); //function console.log(typeof myObj); //object console.log(typeof num3); //objectOne of the things to notice here is that typeof null gives an object. Actually, this is a bug in JavaScript which was introduced during its creation in 1995. But this cannot be rectified anymore because a lot of code in the web depends on it and rectifying it will break a lot of websites.
logo

JavaScript Tutorial

Operators

Just like any other programming language JavaScript have operators, which works generally on two operands. If there is an expression 5 + 6 then 5 and 6 are operands and + is the operator.

JavaScript supports the following types of operators.

  • Arithmetic Operators
  • Comparison Operators
  • Logical (or Relational) Operators
  • Assignment Operators
  • Conditional (or ternary) Operators

Let’s now look into them in detail.

Arithmetic Operators

JS supports the following arithmetic operators.

Addition(+)

It adds two operands if they are number. In case one or both operands are string, it will concatenate them.

var a = 10;
var b = 20;
console.log(a + b); //30
var str = "stingValue";
console.log(a + str); //10stingValue

Substraction(-)

It subtracts the second operand from the first.

var a = 10;
var b = 20;
console.log(a - b); //-10

Multiplication(*)

It multiplies both operands.

var a = 10;
var b = 20;
console.log(a * b); //200

Division(/)

It divides the numerator by the denominator.

var a = 20;
var b = 10;
var c = 3;
console.log(a / b); //2
console.log(a / c); //6.666666666666667

Modulus(%)

It outputs the remainder which we get when we divide the numerator by the denominator.

var a = 20;
var b = 10;
var c = 3;
console.log(a / b); //2
console.log(a / c); //6.666666666666667

Increment(++)

It is one of the few operators which works on only one operand. It is used to increase the integer value by 1.
One thing to notice that it behaves a bit different if used before or after the operand as shown in below code. If we use it before the operand, it updates the variable value instantly.
Whether as if we use it after the operand, it increases the value in memory but don’t update instantly.

var a = 20;
var b = 10;
console.log(++a); //21
console.log(b++); //10
console.log(a);   //21
console.log(b);   //11

Decrement(--)

It works like the increment operator. It is used to decrease the integer value by 1.

var a = 20;
var b = 10;
console.log(--a); //19
console.log(b--); //10
console.log(a);   //19
console.log(b);   //9

Comparison Operators

JS supports the following comparison operators.

Equal(==)

Compares where two operands are equal or not. Returns a Boolean true or false depending on the comparison.
One thing to notice is that, if one of the operands to compare is different it converts it to number. Here, variable a and c are different because a is number and c is a string. But the comparison gives true because c is converted to a number before comparison.

var a = 20;
var b = 10;
var c = '20';
console.log(a == b); //false
console.log(a == c); //true

Strict Equal(===)

Just like the Equal(==) operator, compares where two operands are equal or not. Returns a Boolean true or false depending on the comparison.
But it does a strict comparison. It will not do any type of change for operands before comparing. So, the code with 20 === '20' will produce false.

var a = 20;
var b = 10;
var c = '20';
console.log(a === b); //false
console.log(a === c); //false

Not Equal(!=)

It is the opposite of Equal(==) operator, compares whether two operands are not equal. Returns a Boolean false or true depending on the comparison.
But it doesn’t do a strict comparison. It is just like Equal(==) operator, where it converts if the two operands are not of the same data type. So, the code with 20 != '20' will produce false.

var a = 20;
var b = 10;
var c = '20';
console.log(a != b); //true
console.log(a != c); //false

Strict Not Equal(!==)

Just like Not Equal(!=) operator, compares whether two operands are not equal. Returns a Boolean false or true depending on the comparison.
But it does a strict comparison. It will not do any type of change for operands before comparing. So, the code with 20 !== '20' will produce true.

var a = 20;
var b = 10;
var c = '20';
console.log(a !== b); //true
console.log(a !== c); //true

Greater than(>)

The Greater than(>) operator, checks whether the left operand is greater than the value of the right operand. It returns true if it is or else returns false

var a = 20;
var b = 10;
var c = 30;
console.log(a > b); //true
console.log(a > c); //false

Less than(<)

The Less than(>) operator, checks whether the left operand is less than the value of the right operand. It returns true if it is or else returns false

var a = 20;
var b = 10;
var c = 30;
console.log(a < b); //false
console.log(a < c); //true

Greater than or equal to(>=)

The Greater than or equal to(>=) operator, checks whether the left operand is greater than or equal to the value of the right operand. It returns true if it is or else returns false.

var a = 20;
var b = 10;
var c = 30;
var d = 20;
console.log(a >= b); //true
console.log(a >= c); //false
console.log(a >= d); //true

Less than or equal to(<=)

The Less than or equal to(<=) operator, checks whether the left operand is less than or equal to the value of the right operand. It returns true if it is or else returns false.

var a = 20;
var b = 10;
var c = 30;
var d = 20;
console.log(a <= b); //false
console.log(a <= c); //true
console.log(a <= d); //true

Logical Operators

JS supports the following logical operators – Logical AND(&&), Logical OR(||) and Logical Not(!).
We will discuss Logical AND(&&) and Logical OR(||) in detail here because Logical Not(!) just reverses the logical state of its operand. If a condition is true, then the Logical NOT operator will make it false.
Using only the two boolean values true and false, we can generate the truth tables below.
It means logical AND(&&) is only true if both operands are true.
But even if one operand is true in case of logical OR(||), it will return true.

//Logical AND Operation
console.log(true && true);  //true
console.log(true && false); //false
console.log(false && true); //false
console.log(false && false);//false
//Logical OR Operation
console.log(true || true);   //true
console.log(true || false);  //true
console.log(false || true);  //true
console.log(false || false); //false

In JavaScript, the logical operators can operate on expressions of any type, not just booleans. Also, the logical operators do not always return a boolean value

One more thing to understand is that JavaScript considers some values as “falsy” and will always return false. Everything else is “truthy” in JavaScript. The following are the six "falsy" values:

  • false
  • undefined
  • null
  • NaN
  • 0 (both +0 and -0)
  • ""

Both && and || result in the value of (exactly) one of their operands:

  • A && B returns the value A if A is false; otherwise, it returns B.
  • A || B returns the value A if A is true; otherwise, it returns B.

The below code example, shows the same.

console.log(0 || 1);  //1
console.log(1 || 2);  //1
console.log(0 && 1);  //0
console.log(1 && 2);  //2

JavaScript Bitwise Operators

JavaScript bitwise operators works on 32-bit numbers. So, the numeric operands are first converted into 32-bit number. The result is converted back to JavaScript number.

JS supports the following bitwise operators –

Bitwise AND(&)

It performs Boolean AND operation on each bit of the operands.
Eg -

console.log(5 & 1); //1
/* 5 & 1
gets converted into 0101 & 0001,
which will result in 0001 and
it get converted back to decimal 1 */

Bitwise OR(|)

It performs Boolean OR operation on each bit of the operands.
Eg -

console.log(5 | 1); //5
/* 5 | 1
gets converted into 0101 | 0001,
which will result in 0101 and
it get converted back to decimal 5 */

Bitwise NOT(~)

It works on one operand only and reverses all of its bits.
Eg -

console.log(~5); //-6
/* ~5
gets converted into ~00000000000000000000000000000101 ,
which will result in 11111111111111111111111111111010 and
it get converted back to decimal -6 */

Bitwise XOR(^)

It performs Boolean Exclusive OR operation on each bit of the operands.
Eg -

console.log(5 ^ 1); //4
/* 5 ^ 1
gets converted into 0101 ^ 0001,
which will result in 0100 and
it get converted back to decimal 4 */

Left Shift(<<)

It moves all the bits in its first operand to the left by the number of places specified in the second operand. New bits are filled with zeros.
Eg -

console.log(5 << 1); //10
/* 5 << 1
gets converted into 0101 << 1,
which will result in 1010 and
it get converted back to decimal 10 */

Right Shift(>>)

It moves all the bits in its first operand to the right by the number of places specified in the second operand. New bits are filled with zeros.
Eg -

console.log(5 >> 1); //2
/* 5 >> 1
gets converted into 0101 >> 1,
which will result in 0010 and
it get converted back to decimal 2 */

Right Shift with zero(>>>)- h3

This operator is just like the >> operator, except that the bits shifted in on the left are always zero.
Eg -

console.log(5 >>> 1); //2
/* 5 >>> 1
gets converted into 0101 >>> 1,
which will result in 0010 and
it get converted back to decimal 2 */

Assignment Operators

JS supports the following assignment operators –

Simple Assignment(=)

Assigns the value of the right-hand operand to the left-hand operand. The right-hand operand can be a simple number, string or a computation statement. The left operand is generally a variable.
Eg -

var num = 10;
var str = "StringValue";
var res = num + str;
console.log(res); //10StringValue

Add and Assignment(+=)

It adds the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A += B is equivalent to A = A + B
Eg -

var num1 = 10;
var num2 = 5;
num1 += num2;
console.log(num1); //15

Subtract and Assignment(-=)

It subtracts the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A -= B is equivalent to A = A - B
Eg -

var num1 = 10;
var num2 = 5;
num1 -= num2;
console.log(num1); //5

Multiply and Assignment(*=)

It multiplies the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A *= B is equivalent to A = A * B
Eg -

var num1 = 10;
var num2 = 5;
num1 *= num2;
console.log(num1); //50

Divide and Assignment(/=)

It divides the right operand to the left operand and assigns the value to the left operand. Actually, it is a short form of notation. The statement A /= B is equivalent to A = A / B
Eg -

var num1 = 10;
var num2 = 5;
num1 /= num2;
console.log(num1); //2

Modules and Assignment(%=)

It divides the right operand to the left operand and assigns the remainder value to the left operand. Actually, it is a short form of notation. The statement A %= B is equivalent to
A = A % B
Eg -

var num1 = 10;
var num2 = 5;
num1 %= num2;
console.log(num1); //0

Miscellaneous Operators

JS has the following two miscellaneous operators, which doesn’t fit into any category.

Conditional Operator(? :)

The conditional operator is quite similar to if…else statement and can be thought of a short-form to it. The conditional operator first evaluates an expression for a true or false value and then executes the first one if the result is true and the second one if the result is false.
Eg -

var num1 = 10;
var num2 = 5;
var res = num1 > num2 ? 'num1 is greater' : 'num2 is greater';
console.log(res); //num1 is greater

typeof Operator

The typeof operator is a very useful unary operator, which can be used to find the data type any variable.  Let consider the example below and we will see the typeof operator returns correctly the data type of the variables.
Eg -

var num = 10;
var str = "I am String";
var num2;
var bool = true;
var myFunc = function() {};
var myObj = {};
var num3 = null;
console.log(typeof num); //number
console.log(typeof str); //string
console.log(typeof num2); //undefined
console.log(typeof bool); //boolean
console.log(typeof myFunc); //function
console.log(typeof myObj); //object
console.log(typeof num3); //object

One of the things to notice here is that typeof null gives an object. Actually, this is a bug in JavaScript which was introduced during its creation in 1995. But this cannot be rectified anymore because a lot of code in the web depends on it and rectifying it will break a lot of websites.

Leave a Reply

Your email address will not be published. Required fields are marked *

Comments

Janani

I have learned many things from this article. It is beneficial for me. Thank you!

Nilesh Chakrabarty

Nice example for beginners.. I m a beginner so this is very helpful for me ... so plz give this type of beginners example..

michael

This is a great introduction to variables in JavaScript! As a beginner to JavaScript, I found this guide very helpful in understanding the basics of variables and how they are used in JavaScript.

qtsinfo it

Thanks for sharing the information, it is very helpful, I hope to get more such beautiful blogs from you.

knowledge-wisdom

You have shared great information with me i appreciate your work!

Suggested Tutorials

Node JS Tutorial

Build various types of web applications,command-line application,etc.
Node JS Tutorial

Build various types of web applications,command-line application,etc....

Read More

Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introduced by Google corporation in 2012 and was considered to be one of the most promising among JavaScript frameworks. It was written completely in JavaScript to separate an application’s logic from DOM manipulation, aiming at dynamic page updates. Angular introduced many powerful features enabling the developer to effortlessly create rich and single-page applications.Topics CoveredThis Angular tutorial will span over eight modules, each module covering numerous individual aspects that you need to gain complete information about Angular. This set of modules serves as an Angular tutorial for beginners along with experienced IT professionals.Here are the topics that will be covered in the Angular tutorial:Get started with Angular.Learn the basics of Angular.Know what Angular Directives.Get an idea of Component Inputs and Outputs of Angular.Know about Forms in Angular.About Services in Angular.Pipes in Angular.HTTP, Routing and Building in Angular.Who can benefit from this tutorial?This Angular tutorial will be helpful to IT professionals such as:Software Developers, Web Application Programmers and IT Professionals Software Architects and Testing Professionals Career aspirants in web development
Angular JS Tutorial

Introduction: Angular  (What is Angular?)Angular was formerly introdu...

Read More