Introduction
Suppose you have been given the task to write a program that displays the numbers 1–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 9th or 10th 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.
Contents
- While loops
- Do-while loops
- For loops
- Arrays
- For-in loops
- For-of loops
- Review
- Resources
While Loops
While loops will execute a set of statements repeatedly while some condition is 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. The following example will not display anything because our condition is false.
let hungry = false; while (hungry) { console.log("eat"); }
This is the general form of a while loop:
while (condition) { statement; statement; etc. }
One thing to be careful of when using while loops is creating loops that never end. This happens because the condition never becomes false. If it happens to you, your program will crash. Example:
let hungry = true; while (hungry) { console.log("eat"); }
Task
How many times will the body of this loop be executed:
let i = 0; while (i < 10) { console.log("Hello, World"); i += 1; }
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 display “eat” once, even though the condition is false.
let hungry = false; do { console.log("eat"); } while (hungry);
This is the general form for a do while-loop:
do { statement; statement; etc. } while (condition);
Task
Write a do-while loop that will display the numbers 1–10.
For Loops
A for-loop will repeat execution of a code block for a specific number of times. The following example displays the numbers 1–10:
for (let i = 1; i <= 10; i++) { console.log(i); }
This is the general form of a for-loop:
for (initial; condition; step) { statement; statement; etc. }
Initial is an expression that sets the value of our variable. Condition is an expression that must be true for the statements to execute. And step is an expression that increments the value of our variable.
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–10:
let x = 0; for (let i = 1; i <= 10; i++) { x += i; } console.log(x) //55
The +=
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. The following are some common array operations.
Create an empty array:
let arr = [ ];
Initialize an array with values:
let arr = [1, 2, "Hello", "World"];
Get an element from an array:
let arr = [1, 2, "Hello", "World"]; arr[0] //1 arr[2] //"Hello"
Update an element in an array:
let arr = [1, 2, "Hello", "World"]; arr[2] = 3; //[1, 2, 3, "World"]
Loop over an array:
let arr = [1, 2, "Hello", "World"]; for (let i = 0; i < arr.length; i++) { console.log(arr[i]); }
A two-dimensional array is an array whose elements are arrays. Example:
let arr = [ [1, 2], ["Hello", "World"] ]; console.log(arr[ 0 ][ 1 ]); //2
This is how you would loop over the array and display each element:
for (let i = 0; i < arr.length; i++) { for (let j = 0; j < arr[i].length; j++) { console.log(arr[ i ][ j ]); } }
Task
What element is displayed when i = 1 and j = 0 in the above for loop?
For-In Loop
This kind of loop lets us loop through the keys in an object. An object is a data structure that has keys mapped to values. Here are some common operations that can be performed on an object.
Create an empty object:
let obj = { };
Initialize an object with values:
let obj = { foo: "Hello", bar: "World" };
Get a property from an object:
let obj = { foo: "Hello", bar: "World" }; obj.foo; //"Hello" obj["foo"]; //"Hello"
Update a property in an object:
let obj = { foo: "Hello", bar: "World" }; obj.foo = "hi" obj["foo"] = "hi"
Loop over the keys of an object:
for (let key in obj) { console.log(key); }
Task
What does the above for loop display given obj = {foo: "Hello", bar: "World"}?
For-Of Loop
This kind of loop lets us loop over the values of iterable objects. Examples of iterable objects are arrays and strings.
Loop over an array:
let arr = ["foo", "bar", "baz"]; for (let elem of arr) { console.log(elem); } // foo bar baz
Loop over a string:
let str = "Hello"; for (let char of str) { console.log(char); } //'H' 'e' 'l' 'l' 'o'
Task
Using any of the loops, write a program that will display this staircase pattern:
# # # # #
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.
Next, in part 4, we will learn about functions.
Resources
by Alberta Williams via Envato Tuts+ Code
No comments:
Post a Comment