Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 8

JavaScript 

While Loop
The most basic loop in JavaScript is the while loop which would be discussed in this
chapter. The purpose of a while loop is to execute a statement or code block repeatedly
as long as an expression is true. Once the expression becomes false, the loop
terminates.
Flow Chart
The flow chart of while loop looks as follows −

Syntax
The syntax of while loop in JavaScript is as follows −
while (expression) {
Statement(s) to be executed if expression is true
Inc/dec;
}
<html> <html> <!DOCTYPE <html>
<body> <body> html> <body>
<html> <h1>Demo: while
<h2>JavaScript While Loop</h2> <script type = <body> loop</h1>
"text/javascript"> <script> <p id="p0"></p>
<p id="demo"></p> <!-- var i=11; <p id="p1"></p>
var count = while (i<=15) <p id="p2"></p>
<script> 0; { <p id="p3"></p>
let text = ""; document.wri <p id="p4"></p>
let i = 0; document.write("St te(i +
while (i < 10) { arting Loop "); "<br/>"); <script>
text += "<br>The number is " + i; i++; var i =0;
i++; while (count }
} < 10) { </script> while(i < 5)
document.getElementById("demo").in </body> {
nerHTML = text; document.write("Cu </html>
</script> rrent Count : " + document.getElementById("p" +
count + "<br />"); i).innerHTML = i;
</body> count++;
</html> } i++;
}
</script>
document.write("Lo </body>
op stopped!"); </html>
//-->
</script>
<p>Set the
variable to different
value and then
try...</p>
</body>
</html>

Do...while loops in JavaScript


A do...while loop is an exit-controlled loop. This means that the do...while loop executes the block of
code once without checking the condition. After the code has been executed once, the condition is
checked. If the condition is true, the code is executed further. If the condition is false, the loop is
terminated. The do...while statement is used when you want to run a loop at least one time. Here is
the basic syntax for a typical do...while loop.
do {
//code block to be executed
Inc/dec;
}
while (condition);

<html lang="en"> <html> <html> <html> <html>


<head> <head> <body> <body> <body>
<meta <script> <script> <h2>JavaScript Do While <script type =
charset="utf-8"> let a = 9; let a = Loop</h2> "text/javascript">
// while 10; <p id="demo"></p> <!--
<title>JavaScript loop will be // will var count
Do-While executed two execute twice <script> = 0;
Loop</title> times do let text = ""
</head> while (a { let i = 0;
<body> <= 10) document.write("S
<script> { document.writ do { tarting Loop" +
var i = 1; e("do text += "<br>The number is " + i; "<br />");
do { document.write( executed i++; do {
"while executed <br/>"); }
document.write("< <br/>"); a++; while (i < 10); document.write("C
p>The number is " a++; } urrent Count : " +
+ i + "</p>"); } document.getElementById("demo") count + "<br />");
i++; </script> while(a < 12) .innerHTML = text; count++;
} </head> </script> </script> }
while(i <= 5); <body> </body>
</script> <!-- HTML </html> </body> while
</body> body --> </html> (count < 5);
</html> </body>
</html> document.write
("Loop stopped!");
//-->
</script>
<p>Set the
variable to
different value and
then try...</p>
</body>
</html>

JavaScript For Loop
The for loop repeats a block of code as long as a certain condition is met. It is typically used to
execute a block of code for certain number of times. Its syntax is:
for(initialization; condition; increment) {
    // Code to be executed
}
The parameters of the for-loop statement have following meanings:
 initialization — it is used to initialize the counter variables, and evaluated once unconditionally
before the first execution of the body of the loop.
 condition — it is evaluated at the beginning of each iteration. If it evaluates to true, the loop
statements execute. If it evaluates to false, the execution of the loop ends.
 increment — it updates the loop counter with a new value each time the loop runs.
<html lang="en"> <html lang="en"> <html> <html>
<head> <head> <body> <body>
<meta charset="utf-8"> <meta charset="utf- <script> <script type =
<title>JavaScript For 8"> // for loop example "text/javascript">
Loop</title> <title>JavaScript Loop for(let a = 0; a < <!--
</head> through an Array Using 10; a++) { var count;
<body> For-In Loop</title>
<script> </head> document.write("Current document.write("Starting
for(var i=1; i<=5; i++) { <body> value : " + a); Loop" + "<br />");
<script>
document.write("<p>The // An array with some document.write("<br />"); for(count = 0; count
number is " + i + "</p>"); elements } < 10; count++) {
} var fruits = ["Apple", </script>
</script> "Banana", "Mango", </body> document.write("Current
</body> "Orange", "Papaya"]; </html> Count : " + count );
</html>
// Loop through all the document.write("<br />");
elements in the array }
for(var i=0;
i<fruits.length; i++) { document.write("Loop
stopped!");
document.write("<p>" + //-->
fruits[i] + "</p>"); </script>
} <p>Set the variable to
</script> different value and then
</body> try...</p>
</html> </body>
</html>

The for...in Loop


The for-in loop is a special type of a loop that iterates over the properties of an object, or the
elements of an array. The generic syntax of the for-in loop is:
for(variable in object) {
    // Code to be executed
}

The loop counter i.e. variable in the for-in loop is a string, not a number. It contains the name of current
property or the index of the current array element. The following example will show you how to loop
through all properties of a JavaScript object.

<html <html <html> <html>


lang="en"> lang="en"> <body> <body>
<head> <head> <h2>for/in loop in
<meta <meta JavaScript</h2> <h2>JavaScript For In Loop</h2>
charset="utf-8"> charset="utf-8"> <p id="demo"></p> <p>The for in statement loops
<script> through the properties of an
<title>JavaScript <title>JavaScript let txt = ''; object:</p>
Iterate Over an Loop Through // define an object
Array Using For an Array Using let person = {fname:"ram", <p id="demo"></p>
Loop</title> For-In lname:"singh", age:89};
</head> Loop</title> let x; <script>
<body> </head> for(x in person) const person = {fname:"John",
<script> <body> { lname:"Doe", age:25};
// An object <script> // x is the key like fname,
with some // An array lname and age let txt = "";
properties with some txt += person[x] + " "; for (let x in person) {
var person = elements txt += person[x] + " ";
{"name": var fruits = } }
"Clark", ["Apple",
"surname": "Banana", document.getElementById("demo").i document.getElementById("demo").i
"Kent", "age": "Mango", nnerHTML = txt; nnerHTML = txt;
"36"}; "Orange", </script> </script>
"Papaya"]; </body>
// Loop </html> </body>
through all the // Loop </html>
properties in the through all the
object elements in the
for(var prop in array
person) { for(var i in
fruits) {
document.write(
"<p>" + prop + " document.write(
="+ "<p>" + fruits[i] +
person[prop] + "</p>");
"</p>"); }
} </script>
</script> </body>
</body> </html>
</html>

JavaScript Break and Continue


 The break statement "jumps out" of a loop.
 The continue statement "jumps over" one iteration in the loop.

The Break Statement The Continue


It was used to "jump out" of
a   statement. The 
switch()  statement
breakStatement
can also be used to jump out of a loop: The continue statement breaks one
iteration (in the loop), if a specified
condition occurs, and continues with the
next iteration in the loop.
This example skips the value of 3:
<html> <html>
<body> <body>

<h2>JavaScript Loops</h2> <h2>JavaScript Loops</h2>

<p>A loop with a <b>break</b> statement.</p> <p>A loop with a <b>continue</b> statement.</p>

<p id="demo"></p> <p>A loop which will skip the step where i = 3.</p>

<script> <p id="demo"></p>


let text = "";
for (let i = 0; i < 10; i++) { <script>
if (i === 3) { break; } let text = "";
text += "The number is " + i + "<br>"; for (let i = 0; i < 10; i++) {
} if (i === 3) { continue; }
text += "The number is " + i + "<br>";
document.getElementById("demo").innerHTML = text; }
</script> document.getElementById("demo").innerHTML = text;
</script>
</body>
</html> </body>
</html>

JavaScript Arrays
An array is a special variable, which can hold more than one value. JavaScript array is a
special type of variable, which can store multiple values using a
special syntax.

 Array Literal  Get Size of an  Accessing Array


Syntax Array Elements
<html> <html> <html>
<body> <body> <body>
<h1>Demo: JavaScript Arrays</h1> <h1>Demo: Getting Array <h1>Demo: Accessing Array
<p id="p1"></p> Size</h1> Elements in JavaScript</h1>
<p id="p2"></p> <p id="p1"></p> <p id="p1"></p>
<p id="p3"></p> <p id="p2"></p> <p id="p2"></p>
<p id="p4"></p> <p id="p3"></p>
<p id="p5"></p> <script> <p id="p4"></p>
let cities = ["Mumbai", "New York", <p id="p5"></p>
<script> "Paris", "Sydney"]; <p id="p6"></p>
let stringArray = ["one", "two", document.getElementById("p1").inn <p id="p7"></p>
"three"]; erHTML = cities.length; <p id="p8"></p>
<p id="p9"></p>
<p id="p10"></p>
let numericArray = [1, 2, 3, 4]; cities[4] = "Delhi";
document.getElementById("p2").inn
erHTML = cities.length; <script>
let decimalArray = [1.1, 1.2, 1.3];
</script> let numArr = [10, 20, 30, 40, 50];
</body> document.getElementById("p1").inn
let booleanArray = [true, false, false, erHTML = numArr[0];
</html>
true]; document.getElementById("p2").inn
erHTML = numArr[1];
let data = [1, "Steve", "DC", true,
255000, 5.5]; document.getElementById("p3").inn
erHTML = numArr[2];
document.getElementById("p1").inn document.getElementById("p4").inn
erHTML = stringArray; erHTML = numArr[3];
document.getElementById("p2").inn document.getElementById("p5").inn
erHTML = numericArray; erHTML = numArr[4];
document.getElementById("p3").inn
erHTML = decimalArray; let cities = ["Mumbai", "New York",
document.getElementById("p4").inn "Paris", "Sydney"];
erHTML = booleanArray;
document.getElementById("p5").inn document.getElementById("p6").inn
erHTML = data; erHTML = cities[0];
</script> document.getElementById("p7").inn
</body> erHTML = cities[1];
</html> document.getElementById("p8").inn
erHTML = cities[2];
document.getElementById("p9").inn
erHTML = cities[3];

//accessing element from


nonexistance index
document.getElementById("p10").in
nerHTML = cities[4]; // undefined
</script>
</body>
</html>
 Accessing Array  Array.forEach()  Update Array
using at() Elements

<html> <html> <html>
<body> <body> <body>
<h1>Demo: Accessing Array <h1>Demo: Accessing Array <h1>Demo: Update Array Elements
Elements in JavaScript</h1> Elements using for loops</h1> in JavaScript</h1>
<p id="p1"></p> <p id="p1"></p>
<p id="p2"></p> <script> <p id="p2"></p>
<p id="p3"></p> let numArr = [10, 20, 30, 40, 50];
<p id="p4"></p>
<p id="p5"></p>
numArr.forEach(i => <script>
<p id="p6"></p>
console.log(i)); //prints all elements let cities = ["Mumbai", "New York",
<p id="p7"></p>
"Paris", "Sydney"];
<p id="p8"></p>
for(let i=0; i<numArr.length; i++) document.getElementById("p1").inn
<p id="p9"></p>
console.log(numArr[i]); erHTML = cities;
<p id="p10"></p>
<p id="p11"></p>
for(let i of numArr) cities[0] = "Delhi";
console.log(i); cities[1] = "Los angeles";
<script>
let numArr = [10, 20, 30, 40, 50];
document.getElementById("p1").inn for(let i in numArr) document.getElementById("p2").inn
erHTML = numArr.at(0); console.log(numArr[i]); erHTML = cities;
document.getElementById("p2").inn </script> </script>
erHTML = numArr.at(1); </body> </body>
document.getElementById("p3").inn </html> </html>
erHTML = numArr.at(2);
document.getElementById("p4").inn
erHTML = numArr.at(3);
document.getElementById("p5").inn
erHTML = numArr.at(4);

document.getElementById("p6").inn
erHTML = numArr.at(-1);
document.getElementById("p7").inn
erHTML = numArr.at(-2);
document.getElementById("p8").inn
erHTML = numArr.at(-3);
document.getElementById("p9").inn
erHTML = numArr.at(-4);
document.getElementById("p10").in
nerHTML = numArr.at(-5);
document.getElementById("p11").in
nerHTML = numArr.at(-6);
</script>
</body>
</html>
 Adding New  Add Element At  Remove Array
Elements Last using Elements
push()
<html> <html> <html>
<body> <body> <body>
<h1>Demo: Add Array Elements in <h1>Demo: Add Array Elements in <h1>Demo: Remove Last Element
JavaScript</h1> JavaScript</h1> from an Array in JavaScript</h1>
<p id="p1"></p> <p id="p1"></p> <p id="p1"></p>
<p id="p2"></p> <p id="p2"></p> <p id="p2"></p>
<p id="p3"></p> <p id="p3"></p> <p id="p3"></p>
<p id="p4"></p>
<script> <script>
let cities = ["Mumbai", "New York", let cities = ["Mumbai", "New York",
<script> "Paris", "Sydney"]; "Paris", "Sydney"];
let cities = ["Mumbai", "New York", document.getElementById("p1").inn document.getElementById("p1").inn
"Paris", "Sydney"]; erHTML = cities; erHTML = cities;
document.getElementById("p1").inn
erHTML = cities; cities.unshift("Delhi"); //adds new let removedCity = cities.pop();
element at the beginning document.getElementById("p2").inn
cities[4] = "Delhi"; //add new element document.getElementById("p2").inn erHTML = cities;
at last erHTML = cities; document.getElementById("p3").inn
document.getElementById("p2").inn erHTML = removedCity;
erHTML = cities; cities.unshift("London", "Pune"); </script>
//adds new element at the </body>
beginning </html>
cities[cities.length] = "London";//use
length property to specify last index document.getElementById("p3").inn
document.getElementById("p3").inn erHTML = cities;
erHTML = cities; </script>
</body>
</html>
cities[9] = "Pune";
document.getElementById("p4").inn
erHTML = cities;
</script>
</body>
</html>
 Example:  Remove Middle
 Sorting an Array
Remove First Elements
Element :
The shift() method returns the
first element and removes it from
the array.
<html> <html> <html>
<body> <body> <body>
<h1>Demo: Remove First Element <h1>Demo: Remove Middle
from Array in JavaScript</h1> Element from Array in <h2>JavaScript Array Sort</h2>
<p id="p1"></p> JavaScript</h1> <p>The sort() method sorts an array
<p id="p2"></p> <p id="p1"></p> alphabetically:</p>
<p id="p3"></p> <p id="p2"></p>
<p id="p3"></p>
<p id="demo1"></p>
<script> <p id="demo2"></p>
let cities = ["Mumbai", "New York", <script>
"Paris", "Sydney"]; let cities = ["Mumbai", "New York",
<script>
document.getElementById("p1").inn "Paris", "Sydney"];
const fruits = ["Banana", "Orange",
erHTML = cities; document.getElementById("p1").inn "Apple", "Mango"];
erHTML = cities; document.getElementById("demo1")
let removedCity = cities.shift(); .innerHTML = fruits;
document.getElementById("p2").inn let cityToBeRemoved = "Paris";
erHTML = cities; fruits.sort();
document.getElementById("p3").inn let mycities = document.getElementById("demo2")
erHTML = removedCity; cities.filter(function(item) { .innerHTML = fruits;
</script> return item !== cityToBeRemoved </script>
</body> })
</html> document.getElementById("p2").inn </body>
erHTML = mycities; </html>
document.getElementById("p3").inn
erHTML = cities;
</script>
</body>
</html>
 Reversing an  The Compare  Using
Array Function Math.max()/min
() on an Array
<html> <html> <html>
<body> <body> <body>

<h2>JavaScript Array Sort <h2>JavaScript Array Sort</h2> <h2>JavaScript Array Sort</h2>


Reverse</h2>
<p>Click the buttons to sort the <p>The lowest number is <span
<p>The reverse() method reverses array alphabetically or id="demo"></span>.</p>
the elements in an array.</p> numerically.</p>
<p>By combining sort() and <script>
reverse() you can sort an array in <button const points = [40, 100, 1, 5, 25, 10];
descending order:</p> onclick="myFunction1()">Sort document.getElementById("demo").i
Alphabetically</button> nnerHTML = myArrayMin(points);
<p id="demo1"></p> <button
<p id="demo2"></p> onclick="myFunction2()">Sort function myArrayMin(arr) {
Numerically</button> return Math.min.apply(null, arr);
<script> }
// Create and display an array: <p id="demo"></p> </script>
const fruits = ["Banana", "Orange",
"Apple", "Mango"]; <script> </body>
document.getElementById("demo1") const points = [40, 100, 1, 5, 25, </html>
.innerHTML = fruits; 10];
document.getElementById("demo")
// First sort the array .innerHTML = points;
fruits.sort();
function myFunction1() {
// Then reverse it: points.sort();
fruits.reverse(); document.getElementById("demo")
.innerHTML = points;
document.getElementById("demo2") }
.innerHTML = fruits; function myFunction2() {
</script> points.sort(function(a, b){return a -
b});
document.getElementById("demo")
</body>
.innerHTML = points;
</html>
}
</script>

</body>
</html>

You might also like