SlideShare a Scribd company logo
ADMEC MULTIMEDIA
Leader in Animation & Digital Media Education
ISO 9001:2008 CERTIFIED
www.admecindia.co.in
JavaScript Loops
JavaScript performs several types of repetitive operations, called "looping".
Loops are set of instructions used to repeat the same block of code till a
specified condition returns false or true depending on how you need it. To
control the loops you can use counter variable that increments or
decrements with each repetition of the loop.
JavaScript supports different kinds of loops:
 for - The for statements are best used when you want to perform a loop a
specific number of times.
 for/in - loops through the properties of an object
 while - The while statements are best used to perform a loop an undetermined
number of times.
 do/while - loops through a block of code while a specified condition is true
Why Loops and what are the uses of Loops?
Very often when you write code, you want the same block of code to run a
number of times. You can use looping statements in your code to do this.
Loops are handy, if you want to run the same code over and over again, each
time with a different value. You can use loops.
Tips to improve performance of loops:
a. How it’s Typically Written?
I think it’s safe to say that most beginners to intermediate JavaScript
developers will write for…loop like this:
var anchors = document.getElementsByTagName("a");
for (i=0;i<anchors.length;i++){
// do some stuff here
}
b. Fix the spacing :
Here’s how our code looks after correcting all the spacing issues:
var anchors = document.getElementsByTagName("a");
for (i = 0; i < anchors.length; i++) {
// do some stuff here
}
Technically, I didn’t need to put a space after the semicolons, but I did it anyhow
to aid readability. In addition to proper spacing around the operators, JSLint also
requires a space between the closing parenthesis and the opening curly brace.
All these spacing issues are from what I understand, to help avoid using
confusing code that’s prone to accidental errors or code in which errors are hard
to spot.
c. Localize your variable:
After fixing the spacing issues, we can now focus on another error
presented by JSLint: the global variable i. Any variable not defined using
the var statement in JavaScript is global in scope. This is bad practice,
and it can be easily overlooked inside of such a commonly-used bit of
code. So let’s make our variable local using the var keyword.
We could do this a couple of ways, but the following method will suffice
to make JSLint happy:
var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i++) {
// do some stuff here
}
d. Don’t calculate length on each iteration :
As the code is now, the length of anchors is calculated on each loop iteration. In
a large application, and with large values and multiple loops, this can contribute
to performance issues. So although in many small instances this might not
matter, it is best practice to try to cache values before using them. So we can
alter the code to look like this instead:
var anchors = document.getElementsByTagName("a");
for (var i = 0, j = anchors.length; i < j; i ++) {
// do some stuff here
}
Now the value gets calculated only once, and is stored in the variable j.
The For Loop
The JavaScript for loop repeats a series of statements any number of times
and includes an optional loop counter that can be used in the execution of the
statements.
The following is the formal syntax definition:
for ( [initial expression]; [condition]; [update expression]) {
//statements
}
When the, for loop executes, the following occurs:
1. The initializing expression is executed. This expression usually initializes
one or more loop counters, but the syntax allows an expression of any
degree of complexity.
2. The condition expression is evaluated. If the value of condition is true, the
loop statements execute. If the value of condition is false, the for loop
terminates.
3. The update expression increment executes.
4. The statements execute, and control returns to step 2.
Example <!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
for (var i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
From the example above, you can read:
Statement 1 sets a variable before the loop starts (var i = 0).
Statement 2 defines the condition for the loop to run (i must be less than 5).
Statement 3 increases a value (i++) each time the code block in the loop has been
executed.
if/else statement within a for loop
If/else statements allow an action to be carried out if a particular condition is
matched, else a different action will be carried out. So if an if/else statement is
placed within a loop, it’ll run each time the loop does.
The example below shows how the numbers printed from a counter for loop can
be manipulated. I want the loop to tell me which numbers are odd and which are
even; if the number is even, I want (even) to be printed after the number and if it
is odd, I want (odd) to be printed.
Here is the code that can accomplish this and the result – the loop is counting
from 1 to 10 and checking each time it is run to see if the variable value passed in
is divisible by 2 (if it is, it is an even number).
Example
// Create the for loop
for (var i = 1; i <= 10; i ++) {
// If the number is even, print '(even)' after the number
if (i % 2 === 0) {
console.log(i + "(even)");
}
// Otherwise, print '(odd)' after the number
else {
console.log(i + "(odd)");
}
}
Output:
1(odd)
2(even)
3(odd)
4(even)
5(odd)
6(even)
7(odd)
8(even)
9(odd)
10(even)
Nested for loops
For loops can also be nested inside of each other. In my simple example
below, imagine that I want to print out a list that I can record my workouts
on in the gym. I want to do four exercises with three sets each, so I’ll need a
list that will reflect this.
I can use a for loop nested within a for loop to achieve this. I’ll need the first
loop to run four times, and each time it runs, to print out an exercise number.
The loop within it will run three times to create the required number of
sets within each exercise I want to complete so I can tick them off as I do
them.
Example
// Create the first for loop
for (var i = 1; i <= 4; i ++) {
console.log("Exercise " + i + ":");
// Create the second for loop
for (var j = 1; j <= 3; j ++) {
console.log("Set " + j);
}
}
Output:
Exercise 1:
Set 1
Set 2
Set 3
Exercise 2:
Set 1
Set 2
Set 3
Exercise 3:
Set 1
Set 2
Set 3
Exercise 4:
Set 1
Set 2
Set 3
for loop within a function
A for loop can be placed inside a function. This way, parameters can be passed
into the function to be used in the loop.
I am going to illustrate this by creating a loop within a function which will print
times tables of any number from 1x to 5x. In this case it will print the 12 times
table.
Example
// Create the function
var timesTable = function(number) {
// Create the for loop
for (var i = 1; i <= 5; i ++) {
var answer = number * i;
console.log(number + " times " + i + " equals " +
answer);
}
}
timesTable(12);
Output:
12 times 1 equals 12
12 times 2 equals 24
12 times 3 equals 36
12 times 4 equals 48
12 times 5 equals 60
for loop using an array
An array stores multiple pieces of data at the same time. A for loop can
be used to item in an array one by one.
My example below shows how I can print out a list of every flavor
cake that I like. I use an array to store the cake flavors for later use.
Each time the loop runs, it looks at each array item in turn and prints
out “I like *arrayitem* cake“.
Example
// Create the array
var flavours = ["chocolate", "ginger", "carrot", "coffee", "walnut", "banana"];
// Create the for loop
for (var i = 0, flen = flavours.length; i < flen; i ++) {
console.log("I like " + flavours[i] + " cake");
}
Output:
I like chocolate cake
I like ginger cake
I like carrot cake
I like coffee cake
I like walnut cake
I like banana cake
for loop using an array within a function
This example is very similar to the one above, so the way the loop is interacting
with the array is exactly the same. However, it is placed within a function and can
be called as such, with arguments passed in.
Example
// Create the array
var flavours = ["chocolate", "ginger", "carrot", "coffee", "walnut", "banana"];
// Create the function
var cake = function(singleFlavour) {
// Create the for loop
for (var i = 0, flen = flavours.length; i < flen; i ++) {
console.log("I like " + singleFlavour[i] + " cake");
}
};
cake(flavours);
Output:
I like chocolate cake
I like ginger cake
I like carrot cake
I like coffee cake
I like walnut cake
I like banana cake
The For/In Loop
JavaScript includes a variation of the for loop, called a for-in loop, which has special
powers of extracting the names and values of any object property currently in the
browser’s memory. The syntax looks like this:
for (var in object) {
//statements
}
The object parameter is not the string name of an object but a reference to the object
itself. JavaScript delivers an object reference if you provide the name of the object as an
unquoted string, such as window or document. Using the var variable, you can create a
script that extracts and displays the range of properties for any given object.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var txt = "";
var person = {fname:"John", lname:"Doe", age:25};
var x;
for (x in person) {
txt += person[x] + " ";
}
document.getElementById("demo").innerHTML = txt;
</script>
</body>
</html>
Output:
John Doe 25
The While Loop
The for loop is not the only kind of repeat loop you can construct in JavaScript. Another
statement, called a while statement, sets up a loop in a slightly different format. Rather
than providing a mechanism for modifying a loop counter, a while repeat loop assumes that
your script statements will reach a condition that forcibly exits the repeat loop.
The basic syntax for a while loop is
while (condition) {
//statements
}
The condition expression is the same kind that you saw in the middle parameter of the for
loop. You introduce this kind of loop if some condition exists in your code (evaluates to
true) before reaching this loop. The loop then performs some action, which affects that
condition repeatedly until that condition becomes false. At that point, the loop exits, and
script execution continues with statements after the closing brace. If the statements inside
the while loop do not somehow affect the values being tested in condition, your script
never exits, and it becomes stuck in an infinite loop.
Example <!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = "";
var i = 0;
while (i < 5) {
text += "The number is " + I + “<br>”;
i++;
}
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
Note: If you forget to increase the variable used in the condition, the loop will
never end. This will crash your browser.
The Do/While Loop
The do...while loop is similar to the while loop except that the condition check happens
at the end of the loop. This means that the loop will always be executed at least once,
even if the condition is false.
Note the semicolon used at the end of the do...while loop.
An important difference distinguishes the do-while loop from the while loop. In the do-
while loop, the statements in the construction always execute at least one time before
the condition can be tested; in a while loop, the statements may never execute if the
condition tested at the outset evaluates to false. So, just think of the do-while loop as a
while loop where the first statement gets executed no matter what.
Use a do-while loop when you know for certain that the looped statements are free to
run at least one time. If the condition may not be met the first time, use the while loop.
For many instances, the two constructions are interchangeable.
do{
code block to be executed
}while(condition);
Example <!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Click</button>
<p id="demo"></p>
<script>
function myFunction() {
var text = ""
var i = 0;
do {
text += "<br>The number is " + i;
i++;
}
while (i < 5);
document.getElementById("demo").innerHTML = text;
}
</script>
</body>
</html>
Output:
The number is 0
The number is 1
The number is 2
The number is 3
The number is 4
The Break Statement
Some loop constructions perform their job as soon as a certain condition is met, at which
point they have no further need to continue looping through the rest of the values in the
loop counter’s range. A common scenario for this is the cycling of a loop through an entire
array in search of a single entry that matches some criterion. That criterion test is set up as
an if construction inside the loop. If that criterion is met, you break out of the loop and let
the script continue with the more meaningful processing of succeeding statements in the
main flow. To accomplish that exit from the loop, use the break statement.
The break statement breaks the loop and continues executing the code after the loop (if
any):
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
The number is 0
The number is 1
The number is 2
The Continue Statement
One other possibility in a for loop is that you may want to skip execution of the nested
statements for just one condition. In other words, as the loop goes merrily on its way
round and round, executing statements for each value of the loop counter, one value of
that loop counter may exist for which you don’t want those statements to execute.
To accomplish this task, the nested statements need to include an if construction to test
for the presence of the value to skip. When that value is reached, the continue command
tells JavaScript to immediately skip the rest of the body, execute the update statement,
and loop back around to the top of the loop.
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 10; i++) {
if (i === 3) { continue; }
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
</body>
</html>
Output:
The number is 0
The number is 1
The number is 2
The number is 4
The number is 5
The number is 6
The number is 7
The number is 8
The number is 9
You can see the above example skips the value of 3.
Summary
HI, myself Akhilesh Ojha a post graduate in computer science and Web UI developer. I
am excelling my JavaScript, jQuery and AngularJS skills in ADMEC Multimedia Institute
currently on weekends. I was given this to write as a classroom project and I tried my
best to explain Loops in JavaScript with examples. All examples are tested and working
fine. In this article, I explained Loops introduction, types of loops, why loops, uses of
loops, tips to improve performance of loops, for loop, for...in loop, while loop, do...while
loop, break and continue statement.
Contact Us:
ADMEC MULTIMEDIA INSTITUTE
C-7/114, IInd Floor, Sector- 7, Rohini, Delhi- 85
Landmark: Near Rohini East Metro Station
Helpline 1: +91 9811 818 122
Helpline 2: +91 9911 782 350
ADMEC MULTIMEDIA
Leader in Animation & Digital Media Education
ISO 9001:2008 CERTIFIED | ADOBE Testing Center
ADMEC MULTIMEDIA INSTITUTE
For More information you can visit :
http://www.admecindia.co.in
Or email : info@admecindia.co.in
Loops in java script

More Related Content

PDF
JavaScript Looping Statements
Janssen Harvey Insigne
 
PDF
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
ODP
Datatype in JavaScript
Rajat Saxena
 
PDF
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
PPTX
Java script errors &amp; exceptions handling
AbhishekMondal42
 
PDF
javascript objects
Vijay Kalyan
 
PDF
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
PDF
JavaScript - Chapter 5 - Operators
WebStackAcademy
 
JavaScript Looping Statements
Janssen Harvey Insigne
 
Fundamental JavaScript [UTC, March 2014]
Aaron Gustafson
 
Datatype in JavaScript
Rajat Saxena
 
JavaScript Interview Questions 2023
Laurence Svekis ✔
 
Java script errors &amp; exceptions handling
AbhishekMondal42
 
javascript objects
Vijay Kalyan
 
JavaScript - Chapter 7 - Advanced Functions
WebStackAcademy
 
JavaScript - Chapter 5 - Operators
WebStackAcademy
 

What's hot (20)

PDF
Java conditional statements
Kuppusamy P
 
PPT
Looping statements in Java
Jin Castor
 
PPTX
Arrays in java
Arzath Areeff
 
ODP
OOP java
xball977
 
PPTX
Java exception handling
BHUVIJAYAVELU
 
PPTX
Javascript functions
Alaref Abushaala
 
PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPTX
C# Loops
Hock Leng PUAH
 
PPTX
Java Data Types
Spotle.ai
 
PPTX
Java features
Prashant Gajendra
 
PPTX
Loops c++
Shivani Singh
 
PPS
Wrapper class
kamal kotecha
 
PPTX
Exception handling in Java
Abhishek Pachisia
 
PPT
C# Exceptions Handling
sharqiyem
 
PPTX
Java package
CS_GDRCST
 
PPTX
Exception Handling in Java
lalithambiga kamaraj
 
PPT
C#.NET
gurchet
 
PPSX
Javascript variables and datatypes
Varun C M
 
PPTX
Advance Java Topics (J2EE)
slire
 
Java conditional statements
Kuppusamy P
 
Looping statements in Java
Jin Castor
 
Arrays in java
Arzath Areeff
 
OOP java
xball977
 
Java exception handling
BHUVIJAYAVELU
 
Javascript functions
Alaref Abushaala
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
C# Loops
Hock Leng PUAH
 
Java Data Types
Spotle.ai
 
Java features
Prashant Gajendra
 
Loops c++
Shivani Singh
 
Wrapper class
kamal kotecha
 
Exception handling in Java
Abhishek Pachisia
 
C# Exceptions Handling
sharqiyem
 
Java package
CS_GDRCST
 
Exception Handling in Java
lalithambiga kamaraj
 
C#.NET
gurchet
 
Javascript variables and datatypes
Varun C M
 
Advance Java Topics (J2EE)
slire
 
Ad

Viewers also liked (18)

PPTX
Java script basic
Ravi Bhadauria
 
PDF
Loops in JavaScript
Florence Davis
 
PDF
Advanced Object-Oriented JavaScript
ecker
 
PPTX
JavaScript Conditional Statements
Marlon Jamera
 
PPTX
JavaScript Loop: Optimization of Weak Typing
Janlay Wu
 
PDF
Writing MySQL User-defined Functions in JavaScript
Roland Bouman
 
PPT
JavaScript Control Statements I
Reem Alattas
 
PPT
JavaScript Functions
Brian Moschel
 
PDF
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
PDF
Event loops in java script 01 - stack
Vishnu Padmanabhan
 
PPTX
Javascript conditional statements
nobel mujuji
 
PPT
Java Programming: Loops
Karwan Mustafa Kareem
 
PDF
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
PPTX
Form Validation in JavaScript
Ravi Bhadauria
 
PPTX
The Loops
Krishma Parekh
 
PPTX
Presentación JavaScript
Lorenzo Morillas Tomás
 
PDF
10 ejercicios-de-do-while
Delvi Ramirez
 
PPTX
Javascript Function
xxbeta
 
Java script basic
Ravi Bhadauria
 
Loops in JavaScript
Florence Davis
 
Advanced Object-Oriented JavaScript
ecker
 
JavaScript Conditional Statements
Marlon Jamera
 
JavaScript Loop: Optimization of Weak Typing
Janlay Wu
 
Writing MySQL User-defined Functions in JavaScript
Roland Bouman
 
JavaScript Control Statements I
Reem Alattas
 
JavaScript Functions
Brian Moschel
 
Design patterns in java script, jquery, angularjs
Ravi Bhadauria
 
Event loops in java script 01 - stack
Vishnu Padmanabhan
 
Javascript conditional statements
nobel mujuji
 
Java Programming: Loops
Karwan Mustafa Kareem
 
Lecture 3 Conditionals, expressions and Variables
Syed Afaq Shah MACS CP
 
Form Validation in JavaScript
Ravi Bhadauria
 
The Loops
Krishma Parekh
 
Presentación JavaScript
Lorenzo Morillas Tomás
 
10 ejercicios-de-do-while
Delvi Ramirez
 
Javascript Function
xxbeta
 
Ad

Similar to Loops in java script (20)

PPTX
JavaScript Session 3
Muhammad Ehtisham Siddiqui
 
DOCX
Loops and iteration.docx
NkurikiyimanaGodefre
 
PPTX
Loops (Refined).pptx
chimkwuogworordu
 
PPTX
FFW Gabrovo PMG - JavaScript 2
Toni Kolev
 
PPTX
Week 6 java script loops
brianjihoonlee
 
PPTX
10. session 10 loops and arrays
Phúc Đỗ
 
PPTX
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
PDF
CoffeeScript
Scott Leberknight
 
PDF
Handout - Introduction to Programming
Cindy Royal
 
PDF
Lecture 03 - JQuery.pdf
Lê Thưởng
 
PPTX
For
sidneyodingo
 
PDF
The Future of JavaScript (SXSW '07)
Aaron Gustafson
 
PDF
Fewd week5 slides
William Myers
 
DOC
Web programming[10]
Muhammad Awaluddin
 
PPS
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
PPTX
06-Control-Statementskkkkkkkkkkkkkk.pptx
kamalsmail1
 
PPTX
Week 7 html css js
brianjihoonlee
 
PDF
1660213363910.pdf
CuentaTemporal4
 
PPTX
JavaScript Proven Practises
Robert MacLean
 
PDF
GDI Seattle - Intro to JavaScript Class 2
Heather Rock
 
JavaScript Session 3
Muhammad Ehtisham Siddiqui
 
Loops and iteration.docx
NkurikiyimanaGodefre
 
Loops (Refined).pptx
chimkwuogworordu
 
FFW Gabrovo PMG - JavaScript 2
Toni Kolev
 
Week 6 java script loops
brianjihoonlee
 
10. session 10 loops and arrays
Phúc Đỗ
 
JS Control Statements and Functions.pptx
Ramakrishna Reddy Bijjam
 
CoffeeScript
Scott Leberknight
 
Handout - Introduction to Programming
Cindy Royal
 
Lecture 03 - JQuery.pdf
Lê Thưởng
 
The Future of JavaScript (SXSW '07)
Aaron Gustafson
 
Fewd week5 slides
William Myers
 
Web programming[10]
Muhammad Awaluddin
 
CS101- Introduction to Computing- Lecture 29
Bilal Ahmed
 
06-Control-Statementskkkkkkkkkkkkkk.pptx
kamalsmail1
 
Week 7 html css js
brianjihoonlee
 
1660213363910.pdf
CuentaTemporal4
 
JavaScript Proven Practises
Robert MacLean
 
GDI Seattle - Intro to JavaScript Class 2
Heather Rock
 

More from Ravi Bhadauria (20)

PDF
3 Important Terms of Post Production
Ravi Bhadauria
 
PDF
Basics of Video Editing | Types of Video Editing | Video Production Process
Ravi Bhadauria
 
PDF
Basics of Media | Types of Media | Units in Media | Software in Media | Color...
Ravi Bhadauria
 
PPTX
History of Visual Communication | Guide to Visual Communication by ADMEC Mult...
Ravi Bhadauria
 
PPTX
Elements and Principles of Design (Updated)
Ravi Bhadauria
 
PDF
Top Graphic Designing Hacks to Make You a Designing Pro Today
Ravi Bhadauria
 
PDF
12 Famous Typographers to Inspire You
Ravi Bhadauria
 
PPTX
Sargam UI Design
Ravi Bhadauria
 
PDF
Use of Shapes in Graphic Design | Psychology of Shapes by ADMEC (Updated)
Ravi Bhadauria
 
PDF
UX Design Essential Theories
Ravi Bhadauria
 
PPTX
Top 10 Ad Gurus
Ravi Bhadauria
 
PDF
Workshop on resume, portfolio, interview
Ravi Bhadauria
 
PDF
Top 10 Architecture Design Colleges in India
Ravi Bhadauria
 
PDF
User interface and user experience ui ux design basics
Ravi Bhadauria
 
PDF
How to create Frost Neon Effect in Photoshop?
Ravi Bhadauria
 
PPTX
Top 10 design colleges and institutes of india
Ravi Bhadauria
 
PPTX
Best Hollywood poster designers
Ravi Bhadauria
 
PDF
Design Principles for All the Designers
Ravi Bhadauria
 
PDF
Content Writing Tips for SEO
Ravi Bhadauria
 
PDF
6 Great Steps to Know to Create Successful Web GUI
Ravi Bhadauria
 
3 Important Terms of Post Production
Ravi Bhadauria
 
Basics of Video Editing | Types of Video Editing | Video Production Process
Ravi Bhadauria
 
Basics of Media | Types of Media | Units in Media | Software in Media | Color...
Ravi Bhadauria
 
History of Visual Communication | Guide to Visual Communication by ADMEC Mult...
Ravi Bhadauria
 
Elements and Principles of Design (Updated)
Ravi Bhadauria
 
Top Graphic Designing Hacks to Make You a Designing Pro Today
Ravi Bhadauria
 
12 Famous Typographers to Inspire You
Ravi Bhadauria
 
Sargam UI Design
Ravi Bhadauria
 
Use of Shapes in Graphic Design | Psychology of Shapes by ADMEC (Updated)
Ravi Bhadauria
 
UX Design Essential Theories
Ravi Bhadauria
 
Top 10 Ad Gurus
Ravi Bhadauria
 
Workshop on resume, portfolio, interview
Ravi Bhadauria
 
Top 10 Architecture Design Colleges in India
Ravi Bhadauria
 
User interface and user experience ui ux design basics
Ravi Bhadauria
 
How to create Frost Neon Effect in Photoshop?
Ravi Bhadauria
 
Top 10 design colleges and institutes of india
Ravi Bhadauria
 
Best Hollywood poster designers
Ravi Bhadauria
 
Design Principles for All the Designers
Ravi Bhadauria
 
Content Writing Tips for SEO
Ravi Bhadauria
 
6 Great Steps to Know to Create Successful Web GUI
Ravi Bhadauria
 

Recently uploaded (20)

PDF
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PPTX
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PPT
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
PPTX
Strengthening open access through collaboration: building connections with OP...
Jisc
 
PDF
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
PPTX
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PDF
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
PPTX
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
PPTX
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
PPTX
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
Odoo 18 Sales_ Managing Quotation Validity
Celine George
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Sandeep Swamy
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Python Programming Unit II Control Statements.ppt
CUO VEERANAN VEERANAN
 
Strengthening open access through collaboration: building connections with OP...
Jisc
 
Types of Literary Text: Poetry and Prose
kaelandreabibit
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
Skill Development Program For Physiotherapy Students by SRY.pptx
Prof.Dr.Y.SHANTHOSHRAJA MPT Orthopedic., MSc Microbiology
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Wings of Fire Book by Dr. A.P.J Abdul Kalam Full PDF
hetalvaishnav93
 
Measures_of_location_-_Averages_and__percentiles_by_DR SURYA K.pptx
Surya Ganesh
 
vedic maths in python:unleasing ancient wisdom with modern code
mistrymuskan14
 
IMMUNIZATION PROGRAMME pptx
AneetaSharma15
 
An introduction to Prepositions for beginners.pptx
drsiddhantnagine
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 

Loops in java script

  • 1. ADMEC MULTIMEDIA Leader in Animation & Digital Media Education ISO 9001:2008 CERTIFIED www.admecindia.co.in
  • 2. JavaScript Loops JavaScript performs several types of repetitive operations, called "looping". Loops are set of instructions used to repeat the same block of code till a specified condition returns false or true depending on how you need it. To control the loops you can use counter variable that increments or decrements with each repetition of the loop. JavaScript supports different kinds of loops:  for - The for statements are best used when you want to perform a loop a specific number of times.  for/in - loops through the properties of an object  while - The while statements are best used to perform a loop an undetermined number of times.  do/while - loops through a block of code while a specified condition is true
  • 3. Why Loops and what are the uses of Loops? Very often when you write code, you want the same block of code to run a number of times. You can use looping statements in your code to do this. Loops are handy, if you want to run the same code over and over again, each time with a different value. You can use loops. Tips to improve performance of loops: a. How it’s Typically Written? I think it’s safe to say that most beginners to intermediate JavaScript developers will write for…loop like this: var anchors = document.getElementsByTagName("a"); for (i=0;i<anchors.length;i++){ // do some stuff here }
  • 4. b. Fix the spacing : Here’s how our code looks after correcting all the spacing issues: var anchors = document.getElementsByTagName("a"); for (i = 0; i < anchors.length; i++) { // do some stuff here } Technically, I didn’t need to put a space after the semicolons, but I did it anyhow to aid readability. In addition to proper spacing around the operators, JSLint also requires a space between the closing parenthesis and the opening curly brace. All these spacing issues are from what I understand, to help avoid using confusing code that’s prone to accidental errors or code in which errors are hard to spot.
  • 5. c. Localize your variable: After fixing the spacing issues, we can now focus on another error presented by JSLint: the global variable i. Any variable not defined using the var statement in JavaScript is global in scope. This is bad practice, and it can be easily overlooked inside of such a commonly-used bit of code. So let’s make our variable local using the var keyword. We could do this a couple of ways, but the following method will suffice to make JSLint happy: var anchors = document.getElementsByTagName("a"); for (var i = 0; i < anchors.length; i++) { // do some stuff here }
  • 6. d. Don’t calculate length on each iteration : As the code is now, the length of anchors is calculated on each loop iteration. In a large application, and with large values and multiple loops, this can contribute to performance issues. So although in many small instances this might not matter, it is best practice to try to cache values before using them. So we can alter the code to look like this instead: var anchors = document.getElementsByTagName("a"); for (var i = 0, j = anchors.length; i < j; i ++) { // do some stuff here } Now the value gets calculated only once, and is stored in the variable j.
  • 8. The JavaScript for loop repeats a series of statements any number of times and includes an optional loop counter that can be used in the execution of the statements. The following is the formal syntax definition: for ( [initial expression]; [condition]; [update expression]) { //statements } When the, for loop executes, the following occurs: 1. The initializing expression is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity. 2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates. 3. The update expression increment executes. 4. The statements execute, and control returns to step 2.
  • 9. Example <!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click</button> <p id="demo"></p> <script> function myFunction() { var text = ""; for (var i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; } </script> </body> </html>
  • 10. Output: The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 From the example above, you can read: Statement 1 sets a variable before the loop starts (var i = 0). Statement 2 defines the condition for the loop to run (i must be less than 5). Statement 3 increases a value (i++) each time the code block in the loop has been executed.
  • 11. if/else statement within a for loop If/else statements allow an action to be carried out if a particular condition is matched, else a different action will be carried out. So if an if/else statement is placed within a loop, it’ll run each time the loop does. The example below shows how the numbers printed from a counter for loop can be manipulated. I want the loop to tell me which numbers are odd and which are even; if the number is even, I want (even) to be printed after the number and if it is odd, I want (odd) to be printed. Here is the code that can accomplish this and the result – the loop is counting from 1 to 10 and checking each time it is run to see if the variable value passed in is divisible by 2 (if it is, it is an even number).
  • 12. Example // Create the for loop for (var i = 1; i <= 10; i ++) { // If the number is even, print '(even)' after the number if (i % 2 === 0) { console.log(i + "(even)"); } // Otherwise, print '(odd)' after the number else { console.log(i + "(odd)"); } } Output: 1(odd) 2(even) 3(odd) 4(even) 5(odd) 6(even) 7(odd) 8(even) 9(odd) 10(even)
  • 13. Nested for loops For loops can also be nested inside of each other. In my simple example below, imagine that I want to print out a list that I can record my workouts on in the gym. I want to do four exercises with three sets each, so I’ll need a list that will reflect this. I can use a for loop nested within a for loop to achieve this. I’ll need the first loop to run four times, and each time it runs, to print out an exercise number. The loop within it will run three times to create the required number of sets within each exercise I want to complete so I can tick them off as I do them. Example // Create the first for loop for (var i = 1; i <= 4; i ++) { console.log("Exercise " + i + ":"); // Create the second for loop for (var j = 1; j <= 3; j ++) { console.log("Set " + j); } }
  • 14. Output: Exercise 1: Set 1 Set 2 Set 3 Exercise 2: Set 1 Set 2 Set 3 Exercise 3: Set 1 Set 2 Set 3 Exercise 4: Set 1 Set 2 Set 3
  • 15. for loop within a function A for loop can be placed inside a function. This way, parameters can be passed into the function to be used in the loop. I am going to illustrate this by creating a loop within a function which will print times tables of any number from 1x to 5x. In this case it will print the 12 times table. Example // Create the function var timesTable = function(number) { // Create the for loop for (var i = 1; i <= 5; i ++) { var answer = number * i; console.log(number + " times " + i + " equals " + answer); } } timesTable(12);
  • 16. Output: 12 times 1 equals 12 12 times 2 equals 24 12 times 3 equals 36 12 times 4 equals 48 12 times 5 equals 60 for loop using an array An array stores multiple pieces of data at the same time. A for loop can be used to item in an array one by one. My example below shows how I can print out a list of every flavor cake that I like. I use an array to store the cake flavors for later use. Each time the loop runs, it looks at each array item in turn and prints out “I like *arrayitem* cake“.
  • 17. Example // Create the array var flavours = ["chocolate", "ginger", "carrot", "coffee", "walnut", "banana"]; // Create the for loop for (var i = 0, flen = flavours.length; i < flen; i ++) { console.log("I like " + flavours[i] + " cake"); } Output: I like chocolate cake I like ginger cake I like carrot cake I like coffee cake I like walnut cake I like banana cake
  • 18. for loop using an array within a function This example is very similar to the one above, so the way the loop is interacting with the array is exactly the same. However, it is placed within a function and can be called as such, with arguments passed in. Example // Create the array var flavours = ["chocolate", "ginger", "carrot", "coffee", "walnut", "banana"]; // Create the function var cake = function(singleFlavour) { // Create the for loop for (var i = 0, flen = flavours.length; i < flen; i ++) { console.log("I like " + singleFlavour[i] + " cake"); } }; cake(flavours);
  • 19. Output: I like chocolate cake I like ginger cake I like carrot cake I like coffee cake I like walnut cake I like banana cake The For/In Loop
  • 20. JavaScript includes a variation of the for loop, called a for-in loop, which has special powers of extracting the names and values of any object property currently in the browser’s memory. The syntax looks like this: for (var in object) { //statements } The object parameter is not the string name of an object but a reference to the object itself. JavaScript delivers an object reference if you provide the name of the object as an unquoted string, such as window or document. Using the var variable, you can create a script that extracts and displays the range of properties for any given object.
  • 21. Example <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var txt = ""; var person = {fname:"John", lname:"Doe", age:25}; var x; for (x in person) { txt += person[x] + " "; } document.getElementById("demo").innerHTML = txt; </script> </body> </html> Output: John Doe 25
  • 23. The for loop is not the only kind of repeat loop you can construct in JavaScript. Another statement, called a while statement, sets up a loop in a slightly different format. Rather than providing a mechanism for modifying a loop counter, a while repeat loop assumes that your script statements will reach a condition that forcibly exits the repeat loop. The basic syntax for a while loop is while (condition) { //statements } The condition expression is the same kind that you saw in the middle parameter of the for loop. You introduce this kind of loop if some condition exists in your code (evaluates to true) before reaching this loop. The loop then performs some action, which affects that condition repeatedly until that condition becomes false. At that point, the loop exits, and script execution continues with statements after the closing brace. If the statements inside the while loop do not somehow affect the values being tested in condition, your script never exits, and it becomes stuck in an infinite loop.
  • 24. Example <!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click</button> <p id="demo"></p> <script> function myFunction() { var text = ""; var i = 0; while (i < 5) { text += "The number is " + I + “<br>”; i++; } document.getElementById("demo").innerHTML = text; } </script> </body> </html>
  • 25. Output: The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 Note: If you forget to increase the variable used in the condition, the loop will never end. This will crash your browser.
  • 27. The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. Note the semicolon used at the end of the do...while loop. An important difference distinguishes the do-while loop from the while loop. In the do- while loop, the statements in the construction always execute at least one time before the condition can be tested; in a while loop, the statements may never execute if the condition tested at the outset evaluates to false. So, just think of the do-while loop as a while loop where the first statement gets executed no matter what. Use a do-while loop when you know for certain that the looped statements are free to run at least one time. If the condition may not be met the first time, use the while loop. For many instances, the two constructions are interchangeable. do{ code block to be executed }while(condition);
  • 28. Example <!DOCTYPE html> <html> <body> <button onclick="myFunction()">Click</button> <p id="demo"></p> <script> function myFunction() { var text = "" var i = 0; do { text += "<br>The number is " + i; i++; } while (i < 5); document.getElementById("demo").innerHTML = text; } </script> </body> </html>
  • 29. Output: The number is 0 The number is 1 The number is 2 The number is 3 The number is 4 The Break Statement Some loop constructions perform their job as soon as a certain condition is met, at which point they have no further need to continue looping through the rest of the values in the loop counter’s range. A common scenario for this is the cycling of a loop through an entire array in search of a single entry that matches some criterion. That criterion test is set up as an if construction inside the loop. If that criterion is met, you break out of the loop and let the script continue with the more meaningful processing of succeeding statements in the main flow. To accomplish that exit from the loop, use the break statement. The break statement breaks the loop and continues executing the code after the loop (if any):
  • 30. Example <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var text = ""; var i; for (i = 0; i < 10; i++) { if (i === 3) { break; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html> Output: The number is 0 The number is 1 The number is 2
  • 31. The Continue Statement One other possibility in a for loop is that you may want to skip execution of the nested statements for just one condition. In other words, as the loop goes merrily on its way round and round, executing statements for each value of the loop counter, one value of that loop counter may exist for which you don’t want those statements to execute. To accomplish this task, the nested statements need to include an if construction to test for the presence of the value to skip. When that value is reached, the continue command tells JavaScript to immediately skip the rest of the body, execute the update statement, and loop back around to the top of the loop.
  • 32. Example <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var text = ""; var i; for (i = 0; i < 10; i++) { if (i === 3) { continue; } text += "The number is " + i + "<br>"; } document.getElementById("demo").innerHTML = text; </script> </body> </html>
  • 33. Output: The number is 0 The number is 1 The number is 2 The number is 4 The number is 5 The number is 6 The number is 7 The number is 8 The number is 9 You can see the above example skips the value of 3.
  • 34. Summary HI, myself Akhilesh Ojha a post graduate in computer science and Web UI developer. I am excelling my JavaScript, jQuery and AngularJS skills in ADMEC Multimedia Institute currently on weekends. I was given this to write as a classroom project and I tried my best to explain Loops in JavaScript with examples. All examples are tested and working fine. In this article, I explained Loops introduction, types of loops, why loops, uses of loops, tips to improve performance of loops, for loop, for...in loop, while loop, do...while loop, break and continue statement.
  • 35. Contact Us: ADMEC MULTIMEDIA INSTITUTE C-7/114, IInd Floor, Sector- 7, Rohini, Delhi- 85 Landmark: Near Rohini East Metro Station Helpline 1: +91 9811 818 122 Helpline 2: +91 9911 782 350 ADMEC MULTIMEDIA Leader in Animation & Digital Media Education ISO 9001:2008 CERTIFIED | ADOBE Testing Center ADMEC MULTIMEDIA INSTITUTE For More information you can visit : http://www.admecindia.co.in Or email : [email protected]