JavaScript Loops

Loops are basically used to iterate a piece of code multiple times. Loops are mostly used in arrays. There are 4 types of loops in JavaScript:

  • for loop
  • for-in loop
  • while loop
  • do-while loop

for loop

for loop is used to iterate a set of statements for a fixed number of times, that is, this loop can be used when number of iterations is used.

Syntax
for (initialization; condition; increment)
{
code to be executed
}

  • initialization: in this, we initialize our counter variable, This statement is executed only once before in the starting of the loop.
  • condition: This will test a condition for true or false. If this condition is true, the statements in the for loop are executed. If the condition becomes false, the statements in the for loop are not executed and control will come out of the loop.
  • increment: Here, we will increase or decrease our counter.

Below is the example of for loop:

document.write("For Loop!!<br/>");
for(i=1; i<=5; i++)
{
document.write(i + "<br/>");
}

Below is the output of the above example:
For Loop!!
1
2
3
4
5

for-in loop

for-in loop is used to loop through the properties of an object or an array element. Here I have used in array in my example.

Below is the example of for-in loop:

document.write("For in loop!! <br/>");
var colors = ["Red", "Orange", "Green", "Blue", "White", "Black"];
var color;
for(color in colors)
{
document.write(colors[color] + "<br/>");
}

Below is the output of the above example:
For in loop!!
Red
Orange
Green
Blue
White
Black

while loop

while loop is used when you are not aware of the number of iteration of the loop.  This loop is executed until the condition in the while loop is true. Once the condition is false, the loop terminates and control will come out of the loop. while loops are almost similar to for loop, the difference is the number of known iterations.

Below is the example of while loop:

document.write("While Loop!! <br/>");
var i = 1;
while(i<6)
{
document.write(i + "<br/>");
i++;
}

Below is the output of the above example:
While Loop!!
1
2
3
4
5

do-while loop

do-while loop is similar to while loop, the only difference is that the do-while loop is executed at least once and the condition is checked at the end of the loop.

Below is the example of while loop:

document.write("Do-While loop!! <br/>");
var i = 1;
do{
document.write(i + "<br/>");
i++;
}while(i<6);

Below is the output of the above example:
Do-While loop!!
1
2
3
4
5

JavaScript Operators

Operators are generally the symbols that are used to perform operations on operands. There are following types of operators in JavaScript:

  • Arithmetic Operators
  • Comparison Operators
  • Logical/Relational Operators
  • Assignment Operators
  • Conditional/Ternary Operators

Lets see these operators in detail:

Arithmetic Operators

These operators are used to perform mathematical operations on numbers. You can also use variables instead of numbers in the below examples.

Operator Description Example
+ Addition: Used to add two numbers. var sum = 10 + 50;
// This will return the value: 60
Subtraction: Used to subtract two numbers. var difference = 100 – 80;
// This will return 20.
* Multiplication: Used to multiply two numbers. var result = 10 * 20;
// This will return 200.
/ Division: Used to divide two numbers. var result = 100/20;
// This will return 5.
% Modulus: Gives the remainder of an integer division.. var result = 100/3;
// This will return 1.
++ Increment: Increases the value of a number by one. var result = +++11;
// This will return 12.
Decrement: Decreases the value of a number by one. var result = –11;
// This will return 10.

Below is an example demonstrating the usage of Arithmetic Operators:

var num1 = 100, num2 = 30, num3 = 20;
var result;
var linebreak = "<br/>";

document.write("<b><u>Arithmetic Operators</u></b>");
document.write(linebreak);

document.write("<b>Addition Operator (+)</b>");
document.write(linebreak);
result = num2 + num3;
document.write(num2 + " + " + num3 + " = " + result);
document.write(linebreak, linebreak);

document.write("<b>Subtraction Operator (-)</b>");
document.write(linebreak);
result = num2 - num3;
document.write(num2 + " - " + num3 + " = " + result);
document.write(linebreak, linebreak);

document.write("<b>Multiplication Operator (*)</b>");
document.write(linebreak);
result = num2 * num3;
document.write(num2 + " * " + num3 + " = " + result);
document.write(linebreak, linebreak);

document.write("<b>Division Operator (/)</b>");
document.write(linebreak);
result = num1 / num3;
document.write(num1 + " / " + num3 + " = " + result);
document.write(linebreak, linebreak);

document.write("<b>Modulus Operator (%)</b>");
document.write(linebreak);
result = num1 % num2;
document.write(num1 + " % " + num2 + " = " + result);
document.write(linebreak, linebreak);

document.write("<b>Increment Operator (++)</b>");
document.write(linebreak);
document.write("++" + num3 + " = " + ++num3)
document.write(linebreak, linebreak);

document.write("<b>Decrement Operator (--)</b>");
document.write(linebreak);
document.write("--" + num2 + " = " + --num2)

Output of the above code is as follows:

Arithmetic Operators

Addition Operator (+)
30 + 20 = 50

Subtraction Operator (-)
30 – 20 = 10

Multiplication Operator (*)
30 * 20 = 600

Division Operator (/)
100 / 20 = 5

Modulus Operator (%)
100 % 30 = 10

Increment Operator (++)
++20 = 21

Decrement Operator (–)
–30 = 29

Comparison Operator

Comparison Operators are used to compare two values and return true or false. You can use these operators in conditional or loop statements. Below are the various comparison operators supported in JavaScript:

Operator Description Example
== Equal: This operator is used to check the equality of two values. X == Y // This will return true if X and Y are equal otherwise return false.
!= Not Equal: This operator is used to check the non-equality of two values. X != Y // This will return true if X and Y are not equal otherwise return false.
> Greater Than: This operator is used to check whether a value is greater than another value or not. X > Y // This will return true if X is greater than Y otherwise return false.
< LessThan: This operator is used to check whether a value is less than another value or not. X < Y // This will return true if X is less than Y otherwise return false.
>= Greater Than or Equal To: This operator is used to check whether a value is greater than or equal to another value or not. X >= Y // This will return true if X is greater than or equal to Y otherwise return false.
<= Greater Than: This operator is used to check whether a value is less than or equal to another value or not. X <= Y // This will return true if X is less than or equal to Y otherwise return false.

Below is an example demonstrating the usage of Comparison Operators:

var num1 = 100, num2 = 30, num3 = 20;
var result;
var linebreak = “<br/>”;

document.write(“<b><u>Comparison Operators</b></u>”);
document.write(linebreak, linebreak);
document.write(“<b>Equal Operator (==)</b>”);
document.write(linebreak);
result = num2 == num3;
document.write(num2 + ” == ” + num3 + ” => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Not Equal Operator (!=)</b>”);
document.write(linebreak);
result = num2 != num3;
document.write(num2 + ” != ” + num3 + ” => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Greater Than Operator (>)</b>”);
document.write(linebreak);
result = num2 > num3;
document.write(num2 + ” > ” + num3 + ” => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Less Than Operator (<)</b>”);
document.write(linebreak);
result = num2 < num3;
document.write(num2 + ” < ” + num3 + ” => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Greater Than or Equal To Operator (>=)</b>”);
document.write(linebreak);
result = num2 >= num2;
document.write(num2 + ” >= ” + num2 + ” => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Less Than or Equal To Operator (<=)</b>”);
document.write(linebreak);
result = num2 <= num1;
document.write(num2 + ” <= ” + num1 + ” => ” + result);

Output of the above code is as follows:

Comparison Operators

Equal Operator (==)
30 == 20 => false

Not Equal Operator (!=)
30 != 20 => true

Greater Than Operator (>)
30 > 20 => true

Less Than Operator (<)
30 < 20 => false

Greater Than or Equal To Operator (>=)
30 >= 30 => true

Less Than or Equal To Operator (<=)
30 <= 100 => true

Logical Operators

They are sometimes used to combine two or more conditions. Are also known as Relational Operators. Below are the various Logical Operators supported in JavaScript:

Operator Description Example
&& Logical AND // Returns true if all the conditions are true. (X && Y) // This will return true if both X and Y are true.
|| Logical OR // Returns true if at least one condition is true (X || Y) // This will return true if either X or Y is true.
! Logical NOT //Returns the opposite of the actual result. (!(X && Y)) // If the result of (X && Y) is true, the the complete statement will return false.

Below is an example demonstrating the usage of Comparison Operators:

var num1 = 100, num2 = 30, num3 = 20;
var result;
var linebreak = “<br/>”;

document.write(“<b><u>Logical Operators</b></u>”);
document.write(linebreak, linebreak);
document.write(“<b>Logical AND (&&)</b>”);
document.write(linebreak);
result = ((num2 > num3) && (num2 < num1));
document.write(“((” + num2 + ” > ” + num3 + ” ) && (” + num2 + ” < ” + num1 + “)) => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Logical OR (||)</b>”);
document.write(linebreak);
result = ((num2 > num3) || (num2 > num1));
document.write(“((” + num2 + ” > ” + num3 + “) || (” + num2 + ” > ” + num1 + “)) => ” + result);
document.write(linebreak, linebreak);

document.write(“<b>Logical NOT (!)</b>”);
document.write(linebreak);
result = !(num2 > num3);
document.write(“!(” + num2 + ” > ” + num3 + “) => ” + result);

Output of the above code is as follows:

Logical Operators

Logical AND (&&)
((30 > 20 ) && (30 < 100)) => true

Logical OR (||)
((30 > 20) || (30 > 100)) => true

Logical NOT (!)
!(30 > 20) => false

Assignment Operator

Assignment operators are used to assign values to variables. Below are various assignment operators supported by JavaScript:

-=Subtract and Assign // It subtracts the right operand from the left operand and then assigns the result to the left operand.a -= b; // This statement will add a and b and then assigns the sum to result variable.

Operator Description Example
= Simple Assignment // It assigns the right operand to the left operand. var result = a; // This statement will assign the value of a to result.
+= Add and Assign // It adds the right operand to the left operand and then assigns the result to the left operand. a += b; // This statement will add a and b and then assigns the result to a => a = a + b
-= Subtract and Assign // It subtracts the right operand from the left operand and then assigns the result to the left operand. a -= b; // This statement will subtract a and b and then assigns the result to a => a = a – b
*= Multiply and Assign // It multiplies the right operand to the left operand and then assigns the result to the left operand. a *= b; // This statement will multiply a and b and then assigns the result to a => a = a * b
/= Divide and Assign // It divides the left operand by the right operand and then assigns the result to the left operand. a /= b; // This statement will divide a by b and then assigns the result to a => a = a / b
%= Modules and Assign // It takes modulus of left and right operand and assigns the result to left operand. a %= b; // This statement will divide a by b and then assigns the remainder to a => a = a % b

Below is an example demonstrating the usage of Comparison Operators:

var num1 = 100, num2 = 30, num3 = 20, num4 = 200, num5 = 30;
var result;

result = num2 + num3; // result = 30 + 20 ==> result = 50
num2 += num3; // num2 = num2 + num3 ==> num2 = 30 + 20 ==> num2 = 50
num2 -= num3; // num2 = num2 – num3 ==> num2 = 50 – 20 ==> num2 = 30 (num2 is 50 from the previous step)
num2 *= num3; // num2 = num2 * num3 ==> num2 = 30 * 20 ==> num2 = 600
num1 /= num3; // num1 = num1 / num3 ==> num1 = 100 / 20 ==> num3 = 5
num4 %= num5; // num4 = num4 % num5 ==> num4 = 200 % 30 ==> num4 = 20

Ternary Operator

This operator is a short form of if…else.
Syntax: condition ? expr1 : expr2
If the condition is true, then expr1 will be evaluated, otherwise expr2 will be evaluated. You can also assign the value of this operator in any variable. Below example will display alert box with text 2018 is NOT a leap year!
var num = 2018;
(num % 4) == 0 ? alert(num + " is a leap year!") : alert(num + " is NOT a leap year!")

Reserved keywords in JavaScript

Reserved keywords are the words which cannot be used as variable names.

Below is the list of such keywords:

abstract boolean break byte case catch
char class const continue debugger default
delete do double else enum export
extends false final finally float for
function goto if implements import in
instanceof int interface 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

JavaScript Variables

Before understanding variables, let’s first understand what are the datatypes. Datatypes are basically the type of value like number, string, boolean.

  • Numbers are like 100, 45, 8990 etc. These values are not included in double quotes. These include both integers and floating-point numbers.
  • String values are like “Hello World”,”This is a test value” etc. These values are included in double quotes.
  • Boolean values include only two values that are true and false.

Variables: Variables are the names in which data is stored in the form of numbers or string values. They are defined by the keyword var. Variables should have unique names and should not be declared twice. For example:

var age = 18;
var name = "David";

Here age, name is the variable in which we are storing the numeric value 18, David. In JavaScript, we do not define the datatype to be stored in variable. It is determined by the value assigned in it. We use Assignment Operator (=) to assign a value to the variable. If we do not assign a value to the variable, it automatically takes the undefined value.

There are two types of variables: Global Variables and Local Variables.

Global Variables: These types of variables have global scope. They can be defined once and used anywhere in the JavaScript code.

Local Variables: These types of variables have local scope. For example, if you define a variable within a function, you can use that variable within that function only. NOTE: Within a function, a local variable will always have priority then the global variable, provided they have the same name.

There are some rules that we use to define the variable names:

  • Variables names can have numbers, alphabets, underscore and dollar sign.
  • Variable names should begin with a letter, but can also begin with a dollar sign or an underscore like _Age or $age. Variable names should not start with a number.
  • Variable names are case-sensitive that is Age and age are different variables.
  • We cannot use reserved words as variable names like if, break, case, switch, var, else etc.

 

JavaScript – Miscellaneous concepts

  • You can declare Global variable without using var keyword, however, it is not recommended to use the Global variables.
  • Like all other programming languages, it is recommended to use CAML-casing nomenclature as first letter small and then for next word capital letter, e.g., salePerMonth. There should not be any space between the words.
  • End all the statements with semicolon (;) like we generally do in other programming languages. Multiple statements can be placed in one single line, separating them using semicolon.
  • There is no fixed datatype to be defined, it is always determined by the type of value assigned to the variable. But yes, we can determine the datatype of the variable using typeof For example: alert(typeof value). As in our example, value contains the string literal, it will show as string. For numbers, it will show number. Numbers are not mentioned in double quotes. If you mention numbers in double quotes, it will become string.
  • You can add 2 numbers using + sign, but in case of string it will concatenate two strings into one string.
  • alert function will not work without round parenthesis.
  • Single line comments are mentioned by using // in the beginning of that line. Multiple line comments start with /* and ends with */. Any statement within the comments will be ignored by JavaScript and will not be executed.

Conditional Statement (switch) in JavaScript

Switch statement is just like if statement with a little modification here and there.

Below is the example of switch. You will get the result as: Front End Language! This time you will not see an alert box displaying the result, instead you will see this text written on the HTML page as we have chosen document.write() function.

var lang="C#";
switch(lang)
{
case "JavaScript":
document.write("Web Development!");
break;
case "C#":
document.write("Front End Language!");
break;
case "SQL":
document.write("Back End language!");
break;
default:
document.write("Not a great choice!");
}

In this, we put condition in switch and then that result is matched with all the subsequent cases. Whichever case value is matched first, those statements will be executed.

break; statement is used to break and come out of that case, so that any other statement won’t be executed.

default: This case is generally placed at the end of all cases and is executed when none of the above cases are matched.

Below is another example where you can put conditions in the cases.

var currentDate = new Date();
var currentHour = currentDate.getHours();
alert("Current Date: " + currentDate);
switch(true)
{
case (currentHour &gt;= 4 &amp;&amp; currentHour &lt; 12):
alert("Morning!");
break;
case (currentHour &gt;= 12 &amp;&amp; currentHour &lt;= 19):
alert("Afternoon!");
break;
case (currentHour &gt; 19 &amp;&amp; currentHour &lt; 4):
alert("Night!");
break;
default:
alert("Invalid value!");
}

Conditional Statements (if…else condition) in JavaScript

This article explains the usage of Conditional Statements like if-else etc in JavaScript. Below codes are explained using Visual Web Developer. You can put this code in a separate .js file (recommended) or can also include in the script tag under head in the HTML file. I am just displaying the conditions and their usage, you can include them in any part of you script.

if condition

if condition is used to check a condition for true or false. The condition to be checked is placed in the round braces after if keyword. If this condition is true, the statements within curly braces of if are executed otherwise not. You can use various operators for the condition like <, > ,>=. <=, == etc. Below is the example

In the below example, you will check if the value in num1 i.e., 10 is greater than 30, then only the alert statement will execute, otherwise not. But this is false, hence you will not see any result with the following statement.

var num1=10;
if(num1 &gt; 30)
{
alert(num1 + " is greater than 30");
}

Now, let’s modify the if condition a little bit. Let’s test for num1 i.e., 10 is less than 30, which is true. Hence you will see an alert box with the message: 10 is less than 30.

var num1=10;
if(num1 &lt; 30)
{
alert(num1 + " is less than 30");
}

Let’s test for equality now. You will see an alert box with the message: 10 is equal to 10.

var num1=10;
if(num1 == 10)
{
alert(num1 + " is equal to 10");
}

Sometimes, we want to execute one or another set of statements based on the result of the condition. Say, execute Statement1 if the condition is true or Statement2 if the condition is false. We use else keyword for this. Below is the example to check whether the number is even or odd.  You will see an alert box with the message: 23 is odd

var num = 23;
if (num % 2 == 0) {
alert(num + " is even.");
}
else {
alert(num + " is odd.");
}

To check multiple conditions, we use if…else if. Now, in the below case even if the second and third conditions are satisfied, it will not execute the third condition as it already got the second condition satisfied first. This is the behavior of if statement that if one condition is satisfied, it won’t even bother to test the following conditions. Hence, the result of the below code is: 15 is less than 20. even if the third condition matches perfectly.

var num = 15;
if (num &gt; 20) {
alert(num + " is greater than 20.");
}
else if (num &lt; 20) {
alert(num + " is less than 20.");
}
else if(num == 15){
alert(num + " is equal to 15.");
}}

We generally put an else in the end to that at least we get a statement that fires if none of the conditions is satisfied. Below code will return: None of the conditions are satisfied.

var num = 15;
if (num &gt; 20) {
alert(num + " is greater than 20.");
}
else if (num == 20) {
alert(num + " is less than 20.");
}
else if(num == 16){
alert(num + " is equal to 15.");
}
else {
alert("None of the conditions are satisfied.");
}

Negation operator (!=): This operator is used to check the inequality of two values.

var num = 23;
if((num % 2) != 0)
{
alert(num + " is odd!");
}

Club two or more conditions

&&: We use this symbol for AND condition. This means the result of if condition is true if all the individual conditions in if are true.

var num1 = 21;
if((num1 % 3 == 0) &amp;&amp; (num1 % 7 == 0))
{
alert(num1 + " is divisible by both 3 and 7!");
}

||: We use this symbol for OR condition. This means the result of if condition is true is any of the individual conditions or all the conditions in if are true.

var num1 = 26;
if((num1 % 13 == 0) || (num1 % 2 == 0))
{
alert(num1 + " is either divible by 2 or 13 or both");
}

Ternary Operator (?:) This operator is a short form of if…else.
Syntax: condition ? expr1 : expr2
If the condition is true, then expr1 will be evaluated, otherwise expr2 will be evaluated. You can also assign the value of this operator in any variable. Below example will display alert box with text 2018 is NOT a leap year!

var num = 2018;
(num % 4) == 0 ? alert(num + " is a leap year!") : alert(num + " is NOT a leap year!")
Power Platform Academy

Start or Upgrade your Career with Power Platform

Learn with Akanksha

Python | Azure | AI/ML | OpenAI | MLOps

Design a site like this with WordPress.com
Get started