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
ODP
Datatype in JavaScript
PDF
javascript objects
PDF
JavaScript Interview Questions 2023
PDF
Fundamental JavaScript [UTC, March 2014]
PPTX
Javascript functions
PPTX
Java script errors &amp; exceptions handling
PPTX
JavaScript New Tutorial Class XI and XII.pptx
JavaScript Looping Statements
Datatype in JavaScript
javascript objects
JavaScript Interview Questions 2023
Fundamental JavaScript [UTC, March 2014]
Javascript functions
Java script errors &amp; exceptions handling
JavaScript New Tutorial Class XI and XII.pptx

What's hot (20)

PPTX
JavaScript Conditional Statements
PPTX
Loop(for, while, do while) condition Presentation
PPT
PHP - Introduction to File Handling with PHP
PDF
JavaScript - Chapter 8 - Objects
PPTX
virtual function
PPTX
Event In JavaScript
PPSX
Javascript variables and datatypes
PPTX
Method overloading
PPTX
Javascript 101
PPSX
Php and MySQL
DOC
String in c
PPTX
Static keyword ppt
PPTX
Inheritance in java
PPTX
String function in my sql
PDF
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
PPTX
Constructor in java
PPTX
Data Types, Variables, and Operators
PPTX
C++ string
PDF
3. Java Script
PPTX
Java constructors
JavaScript Conditional Statements
Loop(for, while, do while) condition Presentation
PHP - Introduction to File Handling with PHP
JavaScript - Chapter 8 - Objects
virtual function
Event In JavaScript
Javascript variables and datatypes
Method overloading
Javascript 101
Php and MySQL
String in c
Static keyword ppt
Inheritance in java
String function in my sql
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Constructor in java
Data Types, Variables, and Operators
C++ string
3. Java Script
Java constructors
Ad

Viewers also liked (18)

PPTX
Java script basic
PDF
Loops in JavaScript
PDF
Advanced Object-Oriented JavaScript
PPTX
JavaScript Loop: Optimization of Weak Typing
PDF
Writing MySQL User-defined Functions in JavaScript
PPT
JavaScript Control Statements I
PPT
JavaScript Functions
PDF
Design patterns in java script, jquery, angularjs
PDF
Event loops in java script 01 - stack
PPTX
Javascript conditional statements
PPT
Java Programming: Loops
PDF
Lecture 3 Conditionals, expressions and Variables
PPTX
Form Validation in JavaScript
PPTX
The Loops
PPTX
Presentación JavaScript
PDF
10 ejercicios-de-do-while
PPT
Looping statements in Java
PPTX
Javascript Function
Java script basic
Loops in JavaScript
Advanced Object-Oriented JavaScript
JavaScript Loop: Optimization of Weak Typing
Writing MySQL User-defined Functions in JavaScript
JavaScript Control Statements I
JavaScript Functions
Design patterns in java script, jquery, angularjs
Event loops in java script 01 - stack
Javascript conditional statements
Java Programming: Loops
Lecture 3 Conditionals, expressions and Variables
Form Validation in JavaScript
The Loops
Presentación JavaScript
10 ejercicios-de-do-while
Looping statements in Java
Javascript Function
Ad

Similar to Loops in java script (20)

PPTX
JavaScript Session 3
DOCX
Loops and iteration.docx
PPTX
Loops (Refined).pptx
PPTX
FFW Gabrovo PMG - JavaScript 2
PPTX
Week 6 java script loops
PPTX
10. session 10 loops and arrays
PPTX
JS Control Statements and Functions.pptx
PDF
CoffeeScript
PDF
Handout - Introduction to Programming
PDF
Lecture 03 - JQuery.pdf
PPTX
PDF
The Future of JavaScript (SXSW '07)
PDF
Fewd week5 slides
DOC
Web programming[10]
PPS
CS101- Introduction to Computing- Lecture 29
PPTX
06-Control-Statementskkkkkkkkkkkkkk.pptx
PPTX
Week 7 html css js
PDF
1660213363910.pdf
PPTX
JavaScript Proven Practises
PDF
GDI Seattle - Intro to JavaScript Class 2
JavaScript Session 3
Loops and iteration.docx
Loops (Refined).pptx
FFW Gabrovo PMG - JavaScript 2
Week 6 java script loops
10. session 10 loops and arrays
JS Control Statements and Functions.pptx
CoffeeScript
Handout - Introduction to Programming
Lecture 03 - JQuery.pdf
The Future of JavaScript (SXSW '07)
Fewd week5 slides
Web programming[10]
CS101- Introduction to Computing- Lecture 29
06-Control-Statementskkkkkkkkkkkkkk.pptx
Week 7 html css js
1660213363910.pdf
JavaScript Proven Practises
GDI Seattle - Intro to JavaScript Class 2

More from Ravi Bhadauria (20)

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

Recently uploaded (20)

PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
Cell Types and Its function , kingdom of life
PDF
FourierSeries-QuestionsWithAnswers(Part-A).pdf
PDF
Pre independence Education in Inndia.pdf
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Basic Mud Logging Guide for educational purpose
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PDF
01-Introduction-to-Information-Management.pdf
PDF
TR - Agricultural Crops Production NC III.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PDF
RMMM.pdf make it easy to upload and study
PDF
Module 4: Burden of Disease Tutorial Slides S2 2025
PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
Cell Types and Its function , kingdom of life
FourierSeries-QuestionsWithAnswers(Part-A).pdf
Pre independence Education in Inndia.pdf
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
O7-L3 Supply Chain Operations - ICLT Program
Microbial diseases, their pathogenesis and prophylaxis
Basic Mud Logging Guide for educational purpose
Final Presentation General Medicine 03-08-2024.pptx
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
01-Introduction-to-Information-Management.pdf
TR - Agricultural Crops Production NC III.pdf
Supply Chain Operations Speaking Notes -ICLT Program
102 student loan defaulters named and shamed – Is someone you know on the list?
RMMM.pdf make it easy to upload and study
Module 4: Burden of Disease Tutorial Slides S2 2025
PPH.pptx obstetrics and gynecology in nursing
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...

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 : info@admecindia.co.in