Loop (Iteration) Statements in JavaScript

Loop(Iteration) Statement

A loop describes the process in a software program/script that repeats the same set of instructions over and over until it receives the order to stop.

Loops offer a quick and easy way to execute something repeatedly. There are 4 types of loop in JavaScript:

  • for statment
  • for/in statement
  • while statment
  • do/while statement

for Statement

The for is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.

Example of for statement

For/in Statement

  • This statement loops through the properties of an object.
  • The block of code snippet inside the loop will be executed once for each of the properties.

While Statement

  • while is a loop statement that is executed as long as the given condition is true. It will not stop until and unless the condition becomes false.
  • Initialization of loop variable is mandatory before writing while loop.

Example of while statment

do-while Loop

  • It loops through a block of code once at first and then repeats the loop while the specified condition is true.
  • The main difference between do-while and while loop is that in do-while loop, the set of statements are executed at least once even if the condition isn’t satisfied whereas in while loop nothing is executed if the condition is false.

Example: of do while statement

Nested Loops

An important fact is that both break and continue affect the current loop.

So while working with the nested loops, things can get confusing very quickly.

Consider the following example below:


  • We have got 2 loops here. Each loop runs for 5 times i.e., 0–4.
  • The first loop will continue if i is even i.e., the only values of i that can ever be logged are 1 & 3 as 0, 2, and 4 will not pass the even criteria: if (i % 2 == 0).
  • Now, the inner lop breaks when j is 2. So, the values of j can only be 0 & 1.

So finally the printed output is:

If Else Statement in JavaScript

Conditional Statements

The conditional statements are used to perform different actions for different decisions.

Just like any other languages, JavaScript has the following conditional statements:

  • if for specifying a block of code to be executed, when a specified condition becomes true
  • else to specify a block of code to be executed, when the condition is false
  • else if (nested if) for specifying a new condition to test, when the first condition becomes false

The if Statement

Use the if statement to specify a block of JavaScript code to be executed when a condition becomes true.

Syntax of if statement


Make a “Good Morning” greeting if the hour is greater than 06:00:

The if else Statement

Use of else statement for specifying a block of code to be executed when the condition becomes false.

Syntax of if else statement

Example of if else

If the hour is less than 12, create a “Good Morning” greeting, otherwise “Good Afternoon”:

The else if Statement

Use else if statement to specify a new condition when the first condition is false.


Example of else if

If time is less than 12:00, create a “Good morning” greeting, if not, but time is less than 18:00, create a “Good day” greeting, otherwise a “Good evening”:

Operator Precedence and associativity in JavaScript

Operator Precedence

Operator precedence determines the order in which operators are evaluated when more than one operator is used in an expression.

The higher an operator’s precedence, the earlier it is evaluated in comparison with the operators with lower precedence.

Consider the following example:

The above expression is evaluated in the order of the multiplication operator (*) at first, then the plus operator (+), and finally, the assignment operator (=), due to their respective precedence order.

Precedence can also be manually overridden using a parenthesis e.g.,

The above mentioned expression has its parenthesis around the plus operator, which alters the precedence thereby evaluating the addition operation first.

Operator Associativity

Associativity determines the way in which the operators having same precedence are parsed e.g.:

Left-associativity (left to right) denotes that it is processed as (a <operator> b) <operator> c, while right-associativity (right to left) denotes it is interpreted as a <operator> (b <operator>c).

Assignment operators are right-associative i.e.,

Here both a and b get the same value 5.

At first, b is set to 5.

Then a is also initialized to 5 i.e., the return value of b = 5(right operand of the assignment).

Operator Precedence Table

In the following table, the highest precedence refers to 20 and to the lowest to 1.

PrecedenceOperator typeAssociativityIndividual operators
19Member Access (dot operator)left-to-right… . …
Computed Member Accessleft-to-right… [ … ]
new (with argument list)n/anew … ( … )
Function Callleft-to-right… ( … )
18new (without argument list)right-to-leftnew …
17Postfix Incrementn/a… ++
Postfix Decrement… —
16Logical NOTright-to-left! …
Bitwise NOT~ …
Unary Plus+ …
Unary Negation– …
Prefix Increment++ …
Prefix Decrement— …
typeoftypeof …
voidvoid …
delete>delete …
awaitawait …
15Exponentiationright-to-left… ** …
14Multiplicationleft-to-right… * …
Division… / …
Remainder… % …
13Additionleft-to-right… + …
Subtraction… – …
12Bitwise Left Shiftleft-to-right… << …
Bitwise Right Shift… >> …
Bitwise Unsigned Right Shift… >>> …
11Less Thanleft-to-right… < …
Less Than Or Equal… <= …
Greater Than… > …
Greater Than Or Equal… >= …
in… in …
instanceof… instanceof …
10Equalityleft-to-right… == …
Inequality… != …
Strict Equality… === …
Strict Inequality… !== …
9Bitwise ANDleft-to-right… & …
8Bitwise XORleft-to-right… ^ …
7Bitwise ORleft-to-right… | …
6Logical ANDleft-to-right… && …
5Logical ORleft-to-right… || …
4Conditionalright-to-left… ? … : …
3Assignmentright-to-left… = …
… += …
… -= …
… **= …
… *= …
… /= …
… %= …
… <<= …
… >>= …
… >>>= …
… &= …
… ^= …
… |= …
2yieldright-to-leftyield …
yield*yield* …
1Comma / Sequenceleft-to-right… , …

Super keyword in Java with uses and examples

What is Super keyword in Java

A Super keyword in java is a keyword used to access immediate parent class instance variable, methods and constructors.

java super keyword used in classes where inheritance hierarchy exists.

Uses of super keyword in Java

In Java super keyword is used when a sub class wants to refer its immediate super (parent) class instance variable, methods and constructors then super keyword can used to access them.

  1. To access parent class hidden instance variable.
  2. To call parent class overridden method.
  3. To call the parent class constructor in java.

A. To access parent class hidden instance variable using super keyword.

In java programming, when a super class and sub class both has a instance variable that has a same name.

Then instance variable of sub class hides it’s super class instance variable.

This problem is known as Instance variable hiding.

We can solve the problem of Instance variable hiding, by using super keyword.

Here base class and child class both contains instance variable i. Value of i is different for both classes.

Here i refers to class Two’s instance variable.

To access class one’s i here super.i is used.

B. To call parent class overridden method using super keyword

In Java programming, when sub class have same method signature and return type as parent has then the method is known as overridden method.

If case of overridden method child class can not access parent class overridden method directly.

If want to access the super class overridden method, then super keyword is used.

Description:  When  triangle.show();  call area().

area() calls Triangle class area().

To call Shape class area(). Include super keyword as super.area()

C. To call the parent class constructor using super keyword in java

In java programming, to call immediate parent class constructor super() can be used.

Parent class constructor must be called from child class constructor and must be first line in constructor call.

syntax to call constructor

super()//call default constructor
super(3,3) //call two integer argument constructor

Note: Call to super class constructor must appears as the first statement with in the sub class.

Description:  When super(i,j); line will execute. super( i, j ) will call it’s immediate super class  A’s constructor. 

Another Example with use of constructor call using super and use of this keyword.


Operators in JavaScript

What is an operator?

Consider a simple expression 2 + 5 equals to 7. Here, 2 and 5 are called operands and the ‘+’ is called operator. JavaScript supports the following 5 types of operators:

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

 Arithmetic Operators

JavaScript supports the following arithmetic operators −

Lets take tow variable  A= 10 B = 20, then −

Sr.No Operator and Description
1 + (Addition) Adds two operands Ex: A + B will give 30
2 – (Subtraction) Subtracts the second operand from the first Ex: A – B will give -10
3 * (Multiplication) Multiply both operands Ex: A * B will give 200
4 / (Division) Divide the numerator by the denominator Ex: B / A will give 2
5 % (Modulus) Outputs the remainder of an integer division Ex: B % A will give 0
6 ++ (Increment) Increases an integer value by one Ex: A++ will give 11
7 — (Decrement) Decreases an integer value by one Ex: A– will give 9

Note − Addition operator (+) can you to add two numbers and also to concat strings . e.g. “a” + 10 will give “a10”.

Comparison Operators

Here is the complete set of JavaScript comparison operators:

(Let’s assume variable a=100 and variable b=200)

Sr No Operators and Description
1 `= = (Equals) Checks whether the values of two operands are equal or not, when yes, then the condition becomes true. Ex: (a==b) is not true.
2 != (Not Equal) Checks whether the values of two operands are equal or not, if the values are equal, then the condition becomes false. Ex: (a!=b) is true.
3 > (Greater than) Compare two numbers if first is greater than second then return true. Ex: (a > b) is not true.
4 < (Less than) Compare two numbers if first is less than second then return true. Ex: (a < b) is true.
5 >= (Greater than or Equal to) Checks if the value of the left operand/expression is greater than or equal to the value of the right operand, when yes, the condition becomes true. Ex: (a >= b) is not true here.
6 <= (Less than or Equal to) It Checks whether the value of the left operand/expression is less than or equal to the value of the right operand, when yes, the condition becomes true. Ex: (a <= b) is true here.

Logical Operators

Here is the complete set of JavaScript logical operators:

(Let’s assume variable A=100 and variable B=200)

Sr No Operators and Description
1 &&(Logical AND) When both the operands are non-zero, the condition is true. Ex: (a&&b) is true.
2 || (Logical OR) When any of the two operands are non-zero, the condition becomes true. Ex: (a||b) is true.
3 !(Logical NOT) Reverses the state of the operand. When a condition is true, then the Logical NOT operator will make it false and vice-versa. Ex: (!a) is false.

Bitwise Operators

Here is the complete set of JavaScript bitwise operators:

(Let’s assume variable a=2 and b=3)

Sr No Operators and Description
1 & (Bitwise AND) It performs Boolean AND operation on each bit of the variable placed after it. Ex: (a&b) is 2.
2 | (BitWise OR) It performs Boolean OR operation on each bit of the integer. Ex: (a | b) is 3.
3 ^ (Bitwise XOR) It performs Boolean exclusive OR operation on each bit of the integer. XOR means either of the operands is true, but not both. Ex: (a^b) is 1.
4 ~ (Bitwise Not) This unary operator operates by reversing all the bits of the operand. Ex: (~b) is -4 here.
5 << (Left Shift) It moves all the bits in its first operand to the left by the number of places specified in the right side expression/operand. New bits are filled with zeroes. Shifting a value left by one position is equivalent to multiplying it by 2. Ex: (a << 1) is 4.
6 >> (Right Shift) The left operand’s value is shifted to the right by the number of bits specified by the right operand/expression. Ex: (a >> 1) is 1.
7 >>> (Right shift with Zero) It’s same as the >> operator, except that the bits shifted in on the left are always zero. Ex: (a >>> 1) is 1.

Assignment Operators

Here is the complete set of JavaScript assignment operators:

Sr No Operators and Description
1 = (Simple Assignment) It assigns values from the right side operand/expression to the left side operand Ex: c= a + b assigns the value of (a+b) into c
2 += (Add and Assignment) It adds the right operand/expression to the left operand and assigns the final result to the left operand. Ex: c+= a is same as c = c + a
3 −= (Subtract and Assignment) It subtracts the right operand/expression from the left operand and assigns the final result to the left operand. Ex: c-= a is same as c=c – a
4 *= (Multiply and Assignment) It multiplies the right operand/expression with the left operand and assigns the final result to the left operand. Ex: c*=a is same as c = c*a
5 /= (Divide and Assignment) It divides the left operand with the right operand/expression and assigns the final result to the left operand. Ex: c /=a is same as c = c/a
6 %= (Modules and Assignment) It takes modulus using two operands/expressions and assigns the final result to the left operand. Ex: c %= a is same as c=c % a

Note: Same logic applies to Bitwise operators also. They’ll become <<=, >>=, >>=, &=, |=, ^=.

Conditional Operator(?  :  )

It is short form of an if-else statement. This operator first checks whether an expression is true or false and then executes one of the two given statements depending upon the result of the evaluated condition i.e., true or false.

Sr No Description
1 ? : (Conditional) Is condition true? Then value is a : otherwise value becomes b

Special Operators

The unary type operator typeof operator is placed just before its single operand, which can be of any datatype.

It determines the datatype of its argument. It returns string. Here is the complete list of the return values for the typeof Operator:

Sr No Type String Returned by typeof
1 Number number
2 String string
3 Boolean boolean
4 Object object
5 Function function
6 Undefined undefined
7 Null object

Type Conversion in JavaScript

JavaScript data type or variables can be converted into a different variable and/or different data type by the following ways:

  • Using JavaScript methods
  • By JavaScript itself (automatically)

Converting Numbers to Strings

Using JavaScript method

The JavaScript function String() can convert numbers into strings.

String() can take any numbers, literals, variables or expressions. Consider the examples given below:

The Number method toString() also does the same.

  • Automatically by JavaScript

Consider the following example:

Converting Booleans to Strings

The JavaScript global function String() can also convert booleans into strings.

The Boolean method toString() acts similarly.

Converting Dates to Strings

The global JavaScript method String() also converts dates into strings. Follow the example below:

The Date method toString() does exactly the same.

Converting Strings to Numbers

The JavaScript global method Number() can convert string into number.

Empty strings are converted to numeric 0.

Anything else is converted into NaN (Not a number).

Converting to Boolean

The conversion rule is as follows:

  • Values that are empty like 0, an empty string, null, undefined and NaN are converted to false.
  • Anything other than these values become true.

For example:

Datatype in JavaScript

JavaScript in Internal File

Like other programming languages, JavaScript also provides 2 different data types to hold different types of values. Here are the two types of data types:

  1. Primitive data type
  2. Non-primitive data type

JavaScript is a dynamic type language, which means the type of the variable doesn’t need to be specified (it is dynamically used by JavaScript engine).

The keyword var is used here to declare a variable.

The datatype is declared when it is initialized with a particular values such as numbers, strings etc. For example:

  1. var a=10000; //holding number  
  2. var b=”JavaScript”;    //holding string  
  3.  var c;           // c is now undefined
  4.  c= 25           // cis a Number    
  5. c = “JavaScript”     //c is string

JavaScript primitive data types

These are the five types of primitive data types in JavaScript:

Data Type Description
String String represents sequence of characters e.g. “JavaScript”
Number Number represents numeric values e.g. 50
Boolean Boolean represents either false or true
Undefined Undefined represents value that can’t be defined like infinity etc
Null Null represents nothing i.e. no value

JavaScript non-primitive data types

The three JavaScript non-primitive data types are as follows:

Data Type Description
Object It represents instance through which we can access members and methods
Array It represents collection of similar data type values

JavaScript String Rules

Quotes can be used inside a string if they don’t match the quotessurrounding the string:

JavaScript evaluates expressions from left to right. Also it mconcatenates numbers with strings in an expression. Few examples are as follows:

DifferenceBetween Undefined and Null

Undefined and null are equal with respect to value but different with respect to type.

The typeof null is object whereas undefined is not an object.

JavaScript Arrays

JavaScript arrays are written with square brackets and the array items are separated by comma.

The following code creates an array called colours and initializes with three colours:

Array index starts with zero, which means the first item is colours[0], second is colours[1], and so on.

JavaScript Objects

JavaScript objects are written with curly braces like the following example below:

Reserved Words in JavaScript

JavaScript reserved words are some reserved words that can’t be used as identifier and are used to identify actions to be performed e.g., the var keyword tells the browser to declare variables in JavaScript.

Here is the list of JavaScript keywords:

abstract arguments await boolean
break byte case catch
char class const continue
debugger default delete do
double else enum eval
export extends false final
finally float for function
goto if implements import
in instanceof int interface
let long native new
null package private protected
public return short static
super switch synchronized this
throw throws transient true
try typeof var void
volatile while with yield

Variables in JavaScript

A JavaScript variable is simply a name of a storage location. There are two types of variables in JavaScript:

  • Local variable
  • Global variable

There are some rules for declaring a JavaScript variable:

  • Name must begin with a letter (a-z or A-Z), underscore ( _ ), or dollar( $ ).
    • After first letter digits (0-9) can be used to construct a variable name.
    • JavaScript variable names are case sensitive e.g., tea, Tea and TEA are different variables.
    • No reserve word must be used as a variable name.

JavaScript local variable

A local variable is declared inside a block { } or function. It is accessible within the function or the block only. If you try to access it from outside, it will throw you an error.

For example:

JavaScript global variable

A  global variable is accessible from anywhere within the script. A global variable must be declared outside the function or declared with window object is.

Consider the example below:

Variable Declaration and Initialization

JavaScript variable must be declared using the var or let keyword.

var one = 1;               // variable stores numeric value 1

var two = ‘two’;       // variable named ‘two’ stores string value ‘two’

var three;  // declared a variable named ‘three’ withoutassigning a value

let num1=23; //num1 stores numeric value 23

Multiple variables can be declared in a single line:

var one = 1, two = ‘two’, three;

JavaScript also allows variable declaration without the keyword var. In that case, a value must be assigned while declaring a variable.

one = 1;

two = ‘two’;

Enabling JavaScript

JavaScript needs to be enabled by the client side browser. Generally,  all the modern browsers have built-in support for JavaScript.  If you disable JavaScript, the text will be changed as the events will not be fired.

How to enable JavaScript?

Different browser has different procedure for enabling JavaScript. Here are the simple steps to turn on or turn off JavaScript described below:

JavaScript in Internet Explorer 

  • Choose Tools, Internet Options from the menu in Internet Explorer.
  • Select Security tab from the dialog box appeared on your screen.
  • Click on the Custom Level button.
  • Scroll down until Scripting option comes.
  • Select Enable button under the Active scripting.
  • Finally click OK and you are done

To disable JavaScript in Internet Explorer, you need to select Disable button under the Active scripting.

JavaScript in Firefox 

  • Open a new tab and type about:config in the address bar.
  • Select I’ll be careful, I promise! From the warning dialog box.
  • In the search bar, search for JavaScript.enabled.
  • Now you will get the option to enable or disableJavaScript by right-clicking on the value of that option select toggle.

When JavaScript.enabled is set to true; it is converted to false upon clicking toggle whereas if JavaScript is disabled; it gets enabled upon clicking toggle.

JavaScript in Chrome 

  • Click on the Chrome menu at the top right corner of your browser screen.
  • Select Settings from the menu.
  • Click on the Show advanced settings option at the end of the page.
  • From the Privacy section, click on the Content settings button.

From the JavaScript section, select Do not allowany site to run JavaScript” or “Allow all sites to run JavaScript(recommended) and you are done.

JavaScript in Opera 

  • Choose Tools → Preferences from the menu bar.
  • Select Advanced option from the appearing dialog box.
  • Choose Content from the listed items.
  • Select Enable JavaScript option.
  • Finally click OK and you are all set for JavaScript support in your Opera.

To disable, just uncheck the Enable JavaScript checkbox.

Warning for Non-JavaScript Browsers

If you want to detect whether JavaScript is enabled or supported by the client’s browser, then you can display a warning message to the client using the <noscript> tags just like the below example:

Upon writing the above code snippet, the text from </noscript> will be displayed on the screen in the cases below:

  • The user’s browser does not support JavaScript or
  • JavaScript is not enabled by the current browser.