Learn to Code With JavaScript: Part 3, Loops

Suppose you have been given the task to write a program that displays the numbers 1 to 100. One way you could accomplish this is to write 100 console.log() statements. But I’m sure you wouldn’t because you would have become fed up by the ninth or tenth line.

The only part that changes in each statement is the number, so there should be a way to write only one statement. And there is with loops. Loops let us perform a set of steps in a code block repeatedly.

While Loops

While loops will execute a set of statements repeatedly while some condition evaluates to true. When the condition is false, the program will exit the loop. This kind of loop tests the condition before performing an iteration. An iteration is an execution of the loop’s body. Here is a basic example of a while loop:

In the above example, we begin by setting x to 10. The condition x > 0 evaluates to true in this case, so the code inside the block is executed. This prints the statement “x is now 10” and decreases the value of x by 1. During the next check, x is equal to 9, which is still greater than 0. So the loop continues. During the last iteration, x ultimately becomes 1, and we print “x is now 1”. After that, x becomes 0, so the condition we are evaluating no longer holds true. Then, we start executing the statement outside the loop and print “Out of the loop.”

This is the general form of a while loop:

One thing to remember when using while loops is not to create loops that never end. This happens because the condition never becomes false. If it happens to you, your program will crash. Here’s an example:

In this case, we are increasing x instead of decreasing, and the value of x is already above 0, so the loop will continue indefinitely.

Task

How many times will the body of this loop be executed?

Do-While Loops

A do-while loop will execute the body of statements first, and then check the condition. This kind of loop is useful when you know you want to run the code at least once. The following example will log the value of x once, even though the condition evaluates to false as x is equal to 0.

I have used a do-while loop in my own projects many times to generate random values and then keep generating them as long as they don’t meet certain criteria. This helps in avoiding duplication due to initialization and then reassignment inside the loop.

This is the general form for a do-while loop:

Task

Write a do-while loop that will display the numbers 1 to 10.

For Loops

A for-loop will repeat the execution of a code block a specific number of times. The following example displays the numbers 1 to 10:

This is the general form of a for-loop:

Initial is an expression that sets the value of our variable or variables. This is an optional expression to do the initialization.

Condition is an expression that must be true for the statements to execute. The statements inside the block are only executed if the condition evaluates to true. Skipping the conditions entirely will result in them always being true, so you will have to exit the loop in some other way.

And step is an expression that increments the value of our variable. This is also optional and executes after all the statements inside the for block have executed. The step expression is generally used to get near the closing conditions of the loop.

You can also write a for loop as an equivalent while loop. All you need to do is move your statements and conditions around a bit. The above for loop could be rewritten as:

One programming pattern is to use a for loop to update the value of a variable with itself and a new value. This example sums the numbers 1 to 10:

Here is the equivalent while loop, which gives the same output:

You should note how I did the increment at the end of the while block instead of at the beginning. Incrementing the looping variable i at the beginning would have given us 65, which is not what we intend to do here.

The += operator is an assignment operator that adds a value back to a variable. This is a list of all the assignment operators:

Operator Example Equivalent
+= x += 2  x = x + 2
-= x -= 2 x = x – 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
%= x %= 2 x = x % 2

Task 

Write a for loop that calculates the factorial of a number. The factor of a number n is the product of all the integers from 1 to n. For example, 4! (4 factorial) is 1 x 2 x 3 x 4, which equals 24.

Arrays

An array is an object that holds a list of items, called elements, which are accessed by their index. The index is the position of the element in the array. The first element is at the 0 index.

Arrays have a property called length that gives you the total number of elements in an array. This means that you can create a for-loop to iterate over the items in an array, as shown below:

A two-dimensional array is an array whose elements are arrays. For example:

This is how you would loop over the array and display each element:

How will you rewrite the above loop so that the printing of array elements starts from the end?

For-Of Loop

One of the most common scenarios when iterating over arrays is that you just start from the beginning and then go over all the elements one at a time until you reach the end. There is a shorter way of writing such for loops as for-of loops.

A for-of loop lets us loop over the values of iterable objects such as arrays, maps, and strings. The for-of loop is basically used to iterate over the property values of an object. Here is the loop from the previous section rewritten as a for-of loop.

Loop over a string:

For-In Loop

This kind of loop lets us loop through the properties of an object. An object is a data structure that has keys mapped to values. Arrays in JavaScript are also objects, so we can use the for-in loop to loop over array properties as well. Let’s first see how to use the for-in loop to iterate over object keys or properties.

Here is an example of looping over an object’s keys with the for-in loop:

Here is an example of looping over an array with the for-in loop:

I would like to add that even though we were able to loop over the array elements using a for-in loop, you should avoid doing so. This is because it is meant to loop over the properties of an object, and if you only want to loop over array indices to get array values, you might get unexpected results in certain situations.

Review

Loops let us reduce duplication in our code. While loops let us repeat an action until a condition is false. A do-while loop will execute at least once. For loops let us repeat an action until will we reach the end of a count. The for-in loop is designed so we can access the keys in an object. The for-of loop is designed so we can get the value of an iterable object. 

In the next part, you will learn about functions.

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials and to learn about new JavaScript libraries.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Alberta Williams

Suppose you have been given the task to write a program that displays the numbers 1 to 100. One way you could accomplish this is to write 100 console.log() statements. But I’m sure you wouldn’t because you would have become fed up by the ninth or tenth line.

The only part that changes in each statement is the number, so there should be a way to write only one statement. And there is with loops. Loops let us perform a set of steps in a code block repeatedly.

While Loops

While loops will execute a set of statements repeatedly while some condition evaluates to true. When the condition is false, the program will exit the loop. This kind of loop tests the condition before performing an iteration. An iteration is an execution of the loop’s body. Here is a basic example of a while loop:

In the above example, we begin by setting x to 10. The condition x > 0 evaluates to true in this case, so the code inside the block is executed. This prints the statement "x is now 10" and decreases the value of x by 1. During the next check, x is equal to 9, which is still greater than 0. So the loop continues. During the last iteration, x ultimately becomes 1, and we print "x is now 1". After that, x becomes 0, so the condition we are evaluating no longer holds true. Then, we start executing the statement outside the loop and print "Out of the loop."

This is the general form of a while loop:

One thing to remember when using while loops is not to create loops that never end. This happens because the condition never becomes false. If it happens to you, your program will crash. Here's an example:

In this case, we are increasing x instead of decreasing, and the value of x is already above 0, so the loop will continue indefinitely.

Task

How many times will the body of this loop be executed?

Do-While Loops

A do-while loop will execute the body of statements first, and then check the condition. This kind of loop is useful when you know you want to run the code at least once. The following example will log the value of x once, even though the condition evaluates to false as x is equal to 0.

I have used a do-while loop in my own projects many times to generate random values and then keep generating them as long as they don't meet certain criteria. This helps in avoiding duplication due to initialization and then reassignment inside the loop.

This is the general form for a do-while loop:

Task

Write a do-while loop that will display the numbers 1 to 10.

For Loops

A for-loop will repeat the execution of a code block a specific number of times. The following example displays the numbers 1 to 10:

This is the general form of a for-loop:

Initial is an expression that sets the value of our variable or variables. This is an optional expression to do the initialization.

Condition is an expression that must be true for the statements to execute. The statements inside the block are only executed if the condition evaluates to true. Skipping the conditions entirely will result in them always being true, so you will have to exit the loop in some other way.

And step is an expression that increments the value of our variable. This is also optional and executes after all the statements inside the for block have executed. The step expression is generally used to get near the closing conditions of the loop.

You can also write a for loop as an equivalent while loop. All you need to do is move your statements and conditions around a bit. The above for loop could be rewritten as:

One programming pattern is to use a for loop to update the value of a variable with itself and a new value. This example sums the numbers 1 to 10:

Here is the equivalent while loop, which gives the same output:

You should note how I did the increment at the end of the while block instead of at the beginning. Incrementing the looping variable i at the beginning would have given us 65, which is not what we intend to do here.

The += operator is an assignment operator that adds a value back to a variable. This is a list of all the assignment operators:

Operator Example Equivalent
+= x += 2  x = x + 2
-= x -= 2 x = x - 2
*= x *= 2 x = x * 2
/= x /= 2 x = x / 2
%= x %= 2 x = x % 2

Task 

Write a for loop that calculates the factorial of a number. The factor of a number n is the product of all the integers from 1 to n. For example, 4! (4 factorial) is 1 x 2 x 3 x 4, which equals 24.

Arrays

An array is an object that holds a list of items, called elements, which are accessed by their index. The index is the position of the element in the array. The first element is at the 0 index.

Arrays have a property called length that gives you the total number of elements in an array. This means that you can create a for-loop to iterate over the items in an array, as shown below:

A two-dimensional array is an array whose elements are arrays. For example:

This is how you would loop over the array and display each element:

How will you rewrite the above loop so that the printing of array elements starts from the end?

For-Of Loop

One of the most common scenarios when iterating over arrays is that you just start from the beginning and then go over all the elements one at a time until you reach the end. There is a shorter way of writing such for loops as for-of loops.

A for-of loop lets us loop over the values of iterable objects such as arrays, maps, and strings. The for-of loop is basically used to iterate over the property values of an object. Here is the loop from the previous section rewritten as a for-of loop.

Loop over a string:

For-In Loop

This kind of loop lets us loop through the properties of an object. An object is a data structure that has keys mapped to values. Arrays in JavaScript are also objects, so we can use the for-in loop to loop over array properties as well. Let's first see how to use the for-in loop to iterate over object keys or properties.

Here is an example of looping over an object's keys with the for-in loop:

Here is an example of looping over an array with the for-in loop:

I would like to add that even though we were able to loop over the array elements using a for-in loop, you should avoid doing so. This is because it is meant to loop over the properties of an object, and if you only want to loop over array indices to get array values, you might get unexpected results in certain situations.

Review

Loops let us reduce duplication in our code. While loops let us repeat an action until a condition is false. A do-while loop will execute at least once. For loops let us repeat an action until will we reach the end of a count. The for-in loop is designed so we can access the keys in an object. The for-of loop is designed so we can get the value of an iterable object. 

In the next part, you will learn about functions.

This post has been updated with contributions from Monty Shokeen. Monty is a full-stack developer who also loves to write tutorials and to learn about new JavaScript libraries.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Alberta Williams


Print Share Comment Cite Upload Translate Updates
APA

Alberta Williams | Sciencx (2017-08-03T15:57:33+00:00) Learn to Code With JavaScript: Part 3, Loops. Retrieved from https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/

MLA
" » Learn to Code With JavaScript: Part 3, Loops." Alberta Williams | Sciencx - Thursday August 3, 2017, https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/
HARVARD
Alberta Williams | Sciencx Thursday August 3, 2017 » Learn to Code With JavaScript: Part 3, Loops., viewed ,<https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/>
VANCOUVER
Alberta Williams | Sciencx - » Learn to Code With JavaScript: Part 3, Loops. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/
CHICAGO
" » Learn to Code With JavaScript: Part 3, Loops." Alberta Williams | Sciencx - Accessed . https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/
IEEE
" » Learn to Code With JavaScript: Part 3, Loops." Alberta Williams | Sciencx [Online]. Available: https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/. [Accessed: ]
rf:citation
» Learn to Code With JavaScript: Part 3, Loops | Alberta Williams | Sciencx | https://www.scien.cx/2017/08/03/learn-to-code-with-javascript-part-3-loops/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.