SlideShare a Scribd company logo
1 of 36
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

What's hot

Looping statement
Looping statementLooping statement
Looping statement
ilakkiya
 
Javascript alert and confrim box
Javascript alert and confrim boxJavascript alert and confrim box
Javascript alert and confrim box
Jesus Obenita Jr.
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
Maitree Patel
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 

What's hot (20)

JavaScript Variables
JavaScript VariablesJavaScript Variables
JavaScript Variables
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
Looping statement
Looping statementLooping statement
Looping statement
 
HTML Forms
HTML FormsHTML Forms
HTML Forms
 
Javascript alert and confrim box
Javascript alert and confrim boxJavascript alert and confrim box
Javascript alert and confrim box
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 
Html forms
Html formsHtml forms
Html forms
 
Html forms
Html formsHtml forms
Html forms
 
JavaScript Promises
JavaScript PromisesJavaScript Promises
JavaScript Promises
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
Php string function
Php string function Php string function
Php string function
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Loops Basics
Loops BasicsLoops Basics
Loops Basics
 
Advanced Cascading Style Sheets
Advanced Cascading Style SheetsAdvanced Cascading Style Sheets
Advanced Cascading Style Sheets
 
JavaScript: Events Handling
JavaScript: Events HandlingJavaScript: Events Handling
JavaScript: Events Handling
 
Java Script ppt
Java Script pptJava Script ppt
Java Script ppt
 
Looping statements
Looping statementsLooping statements
Looping statements
 

Viewers also liked

JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak Typing
Janlay Wu
 
Writing MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptWriting MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScript
Roland Bouman
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
Karwan Mustafa Kareem
 
10 ejercicios-de-do-while
10 ejercicios-de-do-while10 ejercicios-de-do-while
10 ejercicios-de-do-while
Delvi Ramirez
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
Jin Castor
 

Viewers also liked (17)

Java script basic
Java script basicJava script basic
Java script basic
 
Loops in JavaScript
Loops in JavaScriptLoops in JavaScript
Loops in JavaScript
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak Typing
 
Writing MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScriptWriting MySQL User-defined Functions in JavaScript
Writing MySQL User-defined Functions in JavaScript
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements I
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 
Design patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjsDesign patterns in java script, jquery, angularjs
Design patterns in java script, jquery, angularjs
 
Event loops in java script 01 - stack
Event loops in java script 01 - stackEvent loops in java script 01 - stack
Event loops in java script 01 - stack
 
Java Programming: Loops
Java Programming: LoopsJava Programming: Loops
Java Programming: Loops
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and Variables
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
The Loops
The LoopsThe Loops
The Loops
 
Presentación JavaScript
Presentación JavaScriptPresentación JavaScript
Presentación JavaScript
 
10 ejercicios-de-do-while
10 ejercicios-de-do-while10 ejercicios-de-do-while
10 ejercicios-de-do-while
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Javascript Function
Javascript FunctionJavascript Function
Javascript Function
 

Similar to Loops in java script

Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
ch samaram
 

Similar to Loops in java script (20)

Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Java tut1
Java tut1Java tut1
Java tut1
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Java_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.pptJava_Tutorial_Introduction_to_Core_java.ppt
Java_Tutorial_Introduction_to_Core_java.ppt
 
Synapseindia reviews.odp.
Synapseindia reviews.odp.Synapseindia reviews.odp.
Synapseindia reviews.odp.
 
JAVA LOOP.pptx
JAVA LOOP.pptxJAVA LOOP.pptx
JAVA LOOP.pptx
 
Java Tutorial | My Heart
Java Tutorial | My HeartJava Tutorial | My Heart
Java Tutorial | My Heart
 
javaloop understanding what is java.pptx
javaloop understanding what is java.pptxjavaloop understanding what is java.pptx
javaloop understanding what is java.pptx
 
Java tutorials
Java tutorialsJava tutorials
Java tutorials
 
Javascript sivasoft
Javascript sivasoftJavascript sivasoft
Javascript sivasoft
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Java tut1
Java tut1Java tut1
Java tut1
 
Tutorial java
Tutorial javaTutorial java
Tutorial java
 
Java Tut1
Java Tut1Java Tut1
Java Tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
Web programming[10]
Web programming[10]Web programming[10]
Web programming[10]
 
Java tutorial PPT
Java tutorial PPTJava tutorial PPT
Java tutorial PPT
 
Java tutorial PPT
Java tutorial  PPTJava tutorial  PPT
Java tutorial PPT
 

More from Ravi Bhadauria

More from Ravi Bhadauria (20)

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

Recently uploaded

Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
heathfieldcps1
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Unit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptxUnit-V; Pricing (Pharma Marketing Management).pptx
Unit-V; Pricing (Pharma Marketing Management).pptx
 
Asian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptxAsian American Pacific Islander Month DDSD 2024.pptx
Asian American Pacific Islander Month DDSD 2024.pptx
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 

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