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

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

Example

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.

Syntax

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”:

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 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

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.

JavaScript Syntax


JavaScript Keywords

JavaScript keywords 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

Whitespace and Line Breaks in JavaScript

JavaScript ignores spaces, tabs, and newline characters that appear in JavaScript programs.

Spaces, tabs, and newlines can be used freely.

This allows you to format and indent the programs in a neat and consistent way that increases readability.

Optional Semicolons in JavaScript

Generally the statements in JavaScript are followed by a semicolon.

However, JavaScript also allows you to omit this semicolon if each of the statements is placed on a separate line.

For example, the following code snippet can be written without semicolons:

But when written in a single line as follows, semicolons must be used

Case Sensitivity

JavaScript is case-sensitive which means that the JavaScript keywords, variables, function names, and any other identifiers must always be typed maintaining a consistent capitalization of letters.

So the identifiers DATE, date and Date will convey different meanings in JavaScript.

Comments in JavaScript

  • Anything written between a // and the end of a line is treated as a comment and is not executed by JavaScript.
  • Any text between the characters /* and */ is treated as a multiple line comment.
  • JavaScript recognizes the HTML comment opening <!–. JavaScript treats this as a single-line comment, just like the // comment.
  • The HTML comment closing sequence –> is not considered as a comment by JavaScript so it must be written as //–>.

JavaScript Inclusion in HTML File

Javascript in Internal File

  1. You can place JavaScript code on HTML pages anywhere within<html> tags(within <body>tag as well as <head> tag)
  2. JavaScript code must be inside <script> tag for aninternal placement.

Within <head> tag

Within <body> tag

External JavaScript

To use JavaScript from an external file source, all JavaScript source code must be written in a text file with the extension “.js” and then include that file as shown below:

For example, if the following content is already written in the file_name.js file the function  Show can be invoked in your HTML file after including the file_name.js file.

Note: The correct path (using ./ or ../ in front of the filename in src attribute) should be mentioned while including the external .js file otherwise it will throw an error and the file will not be included into the current HTML script.

External JavaScript Advantages

Placing scripts in external files is more advantageous than that of in an internal file:

  • It separates HTML and JavaScript code
  • It makes both HTML and JavaScript code easier to read and maintain
  • Cached JavaScript files can speed up page loading

Absolute Path

External scripts can be included with a full URL which is known as Absolute path. Consider the following example:

<script src=”https://www.abcd.co.in/js/file_name.js”></script>

Relative Path

External scripts can also be referenced with a path relative to the current web page which is known as Relative path. Consider the following example:

<script src=”/js/file_name.js”></script>