The original Creative JavaScript tutorial, covering loops in JavaScript. This tutorial is aimed at creative people with no programming experience who are interested to learn loops JavaScript.
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.
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