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
JavaScript Loop Guide

More Related Content

What's hot

JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays Reem Alattas
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to JavascriptAmit Tyagi
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handlingAbhishekMondal42
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript ProgrammingSehwan Noh
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events WebStackAcademy
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Edureka!
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object ModelWebStackAcademy
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScriptAndres Baravalle
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...Edureka!
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions WebStackAcademy
 

What's hot (20)

JavaScript Arrays
JavaScript Arrays JavaScript Arrays
JavaScript Arrays
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Java script errors &amp; exceptions handling
Java script  errors &amp; exceptions handlingJava script  errors &amp; exceptions handling
Java script errors &amp; exceptions handling
 
Flask – Python
Flask – PythonFlask – Python
Flask – Python
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
MYSQL - PHP Database Connectivity
MYSQL - PHP Database ConnectivityMYSQL - PHP Database Connectivity
MYSQL - PHP Database Connectivity
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
JavaScript Tutorial For Beginners | JavaScript Training | JavaScript Programm...
 
Php introduction
Php introductionPhp introduction
Php introduction
 
Php.ppt
Php.pptPhp.ppt
Php.ppt
 
Javascript
JavascriptJavascript
Javascript
 
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 JavaScript - Chapter 9 - TypeConversion and Regular Expressions  JavaScript - Chapter 9 - TypeConversion and Regular Expressions
JavaScript - Chapter 9 - TypeConversion and Regular Expressions
 

Viewers also liked

Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
JavaScript Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional StatementsMarlon Jamera
 
JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJanlay 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 JavaScriptRoland Bouman
 
JavaScript Control Statements I
JavaScript Control Statements IJavaScript Control Statements I
JavaScript Control Statements IReem Alattas
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsBrian Moschel
 
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, angularjsRavi Bhadauria
 
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 - stackVishnu Padmanabhan
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statementsnobel mujuji
 
Lecture 3 Conditionals, expressions and Variables
Lecture 3   Conditionals, expressions and VariablesLecture 3   Conditionals, expressions and Variables
Lecture 3 Conditionals, expressions and VariablesSyed Afaq Shah MACS CP
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScriptRavi Bhadauria
 
10 ejercicios-de-do-while
10 ejercicios-de-do-while10 ejercicios-de-do-while
10 ejercicios-de-do-whileDelvi Ramirez
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 
Javascript Function
Javascript FunctionJavascript Function
Javascript Functionxxbeta
 

Viewers also liked (19)

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 Conditional Statements
JavaScript Conditional StatementsJavaScript Conditional Statements
JavaScript Conditional Statements
 
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
 
Javascript conditional statements
Javascript conditional statementsJavascript conditional statements
Javascript conditional statements
 
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 JavaScript Loop Guide (20)

Java tut1
Java tut1Java tut1
Java tut1
 
Java tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo CahersiveenJava tut1 Coderdojo Cahersiveen
Java tut1 Coderdojo Cahersiveen
 
Javatut1
Javatut1 Javatut1
Javatut1
 
Java tut1
Java tut1Java tut1
Java tut1
 
Java Tutorial
Java TutorialJava Tutorial
Java Tutorial
 
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
 
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
 
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docxCMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
CMIS 102 Hands-On Lab Week 4OverviewThis hands-on lab all.docx
 
Switch case and looping
Switch case and loopingSwitch case and looping
Switch case and looping
 

More from Ravi Bhadauria

3 Important Terms of Post Production
3 Important Terms of Post Production3 Important Terms of Post Production
3 Important Terms of Post ProductionRavi Bhadauria
 
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 ProcessRavi Bhadauria
 
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...Ravi Bhadauria
 
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...Ravi Bhadauria
 
Elements and Principles of Design (Updated)
Elements and Principles of Design (Updated)Elements and Principles of Design (Updated)
Elements and Principles of Design (Updated)Ravi Bhadauria
 
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 Ravi Bhadauria
 
12 Famous Typographers to Inspire You
12 Famous Typographers to Inspire You12 Famous Typographers to Inspire You
12 Famous Typographers to Inspire YouRavi Bhadauria
 
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)Ravi Bhadauria
 
UX Design Essential Theories
UX Design Essential TheoriesUX Design Essential Theories
UX Design Essential TheoriesRavi Bhadauria
 
Workshop on resume, portfolio, interview
Workshop on resume, portfolio, interviewWorkshop on resume, portfolio, interview
Workshop on resume, portfolio, interviewRavi Bhadauria
 
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 IndiaRavi Bhadauria
 
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 basicsRavi Bhadauria
 
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?Ravi Bhadauria
 
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 indiaRavi Bhadauria
 
Best Hollywood poster designers
Best Hollywood poster designersBest Hollywood poster designers
Best Hollywood poster designersRavi Bhadauria
 
Design Principles for All the Designers
Design Principles for All the DesignersDesign Principles for All the Designers
Design Principles for All the DesignersRavi Bhadauria
 
Content Writing Tips for SEO
Content Writing Tips for SEOContent Writing Tips for SEO
Content Writing Tips for SEORavi Bhadauria
 
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 GUIRavi 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

AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomnelietumpap1
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...JhezDiaz1
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........LeaCamillePacle
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 

Recently uploaded (20)

AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
ENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choomENGLISH6-Q4-W3.pptxqurter our high choom
ENGLISH6-Q4-W3.pptxqurter our high choom
 
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
ENGLISH 7_Q4_LESSON 2_ Employing a Variety of Strategies for Effective Interp...
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........Atmosphere science 7 quarter 4 .........
Atmosphere science 7 quarter 4 .........
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 

JavaScript Loop Guide

  • 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