From b779a7cf6a7ddce631e9bad1ee947ccac64bfb26 Mon Sep 17 00:00:00 2001 From: char Date: Wed, 16 Nov 2022 15:05:34 -0800 Subject: [PATCH 1/9] add curriculum for js loops --- config.yaml | 4 + learning-another-language/js-loops.md | 417 ++++++++++++++++++++++++++ 2 files changed, 421 insertions(+) create mode 100644 learning-another-language/js-loops.md diff --git a/config.yaml b/config.yaml index 779a11b..1ad3a7e 100644 --- a/config.yaml +++ b/config.yaml @@ -182,6 +182,10 @@ Standards: Type: Lesson UID: 71c286a7-12b3-48e3-9e19-816ff8f2d9d4 Path: /learning-another-language/vscode-and-style.md + - + Type: Lesson + UID: e99b585f-062b-46ab-8bc4-9f0d00ebebb0 + Path: /learning-another-language/js-loops.md - Type: Lesson UID: dc804b1c-8bb0-4b72-95f0-080a3b9b9552 diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md new file mode 100644 index 0000000..b39a18d --- /dev/null +++ b/learning-another-language/js-loops.md @@ -0,0 +1,417 @@ +# Looping in Javascript +### Learning Goals +* Understand several different looping mechanisms in JS +* By the end of this, you should be able to: + * Iterate over data in a list, set, or map using several different types of loops + * Understand how to terminate a loop early or skip a loop iteration using the `break` and `continue` keywords + +### What is a loop? + +Loops are used to perform repeated tasks based on a condition. A condition is a statement which can evaluate to either **true** or **false**. A loop will continue running until the condition returns false. + +## 1. `for` loop + +```js +for (initialization; condition; finalExpression) { + // do stuff +} +``` + +The `for-loop` consists of three optional expressions, followed by a block of code: + +- **initialization** - This expression runs before the execution of the first loop. The initialization expression is usually used to create a counter. +- **condition** - This expression is checked each time before the loop runs. If it evaluates to true, the code in the loop is executed. If it evaluates to false, the loop stops. If this expression is omitted, it automatically evaluates to true, and the code block is executed. +- **finalExpression** - This expression is executed after each iteration of the loop. This is usually used to increment (or increase) a counter, but can also be used to decrement (or decrease) a counter. + +### Examples + +**1. Print integers 1 .. 5** +```js +for (let i = 1; i <= 5; i++) { + console.log(i) +} + +// Output: +// 1 +// 2 +// 3 +// 4 +// 5 + +// intialization statement: let i = 1 +// condition statement: i <= 5 +// final expression: i++, equivalent to i = i + 1 +``` + +**2. Use a break statement to exit the loop immediately** +```js +for (let i = 1; i <= 5; i++) { + if (i == 4) { + break; + } + console.log(i) +} + +// Output: +// 1 +// 2 +// 3 +``` + +### Common Pitfall: Exceeding the Bounds of an Array +```js +const arr = [ "foo", "bar", "baz" ]; + +for (let i = 0; i <= arr.length; i++) { + console.log(arr[i]); +} + +// Output: +// foo +// bar +// baz +// undefined + +// In the above example, arr.length = 3, +// so accessing arr[3] leads to an undefined element +``` + +When iterating over an array, it is possible to accidentally exceed the bounds of the array. One thing to note about the indices of an array: + +- The first element of an array is stored at index 0. This is true for JavaScript as well as most other programming languages. Therefore, the index of the last element of an array is equal to `arr.length - 1`. + +When constructing a `for-loop`, there are a couple ways to handle exceeding the bounds of an array. They both involve altering the conditional statement in the `for-loop` to either: + +- `i < arr.length` or +- `i <= arr.length - 1` + +```js +const arr = [ "foo", "bar", "baz" ]; + +// Replace the <= with < in the condition statement +for (let i = 0; i < arr.length; i++) { + console.log(arr[i]); +} + +// Output: +// foo +// bar +// baz + +// Replace arr.length with arr.length - 1 +for (let i = 0; i <= arr.length - 1; i++) { + console.log(arr[i]); +} + +// Output: +// foo +// bar +// baz +``` + +## 2.`for … of` loop +```js +for (variable of object) { + // do something +} +``` + +The `for … of` loop can be used to iterate over arrays, sets, and maps. When using the `for … of` loop, there’s no danger of going out of bounds! The loop will go over each item in the iterable object. + +### Examples + +**1. Iterate over items in a list** +```js +const monsters = [ + "Michael Myers", + "Jason Voorhees", + "Freddy Krueger" +]; + +for (let monster of monsters) { + console.log(monster); +} + +// Output: +// Michael Myers +// Jason Voorhees +// Freddy Krueger +``` + +**2. Iterate over items in a map** +```js +const m = new Map(); +m.set(1, "red"); +m.set(2, "black") + +for (let item of m) { + console.log(item); +} + +// Output: +// [1, red] +// [2, black] +``` + +## 3. `for … in` loop +```js +for (property in object) { + // do stuff +} +``` + +The `for … in` loop iterates over all enumerable properties of an object. The code in the loop is executed for each property in the object. + +### Example +```js +const movies = { + 2008: "The Dark Knight", + 2009: "Avatar", + 2010: "Toy Story 3" +}; + +for (let key in movies) { + console.log(key + ": " + movies[key]); +} + +// Ouput: +// 2008: The Dark Knight +// 2009: Avatar +// 2010: Toy Story 3 +``` + +### Common Pitfall: Unexpected Behavior When Iterating over an Array + +While you can use the `for … in` to iterate over an array, it is recommended to use one of the aforementioned for-loops instead. + +The reason for this is because the `for … in` loop iterates over **all** of the enumerable properties in an object, including any that may be inherited. + +If, for instance, a JS library modifies the `Array` prototype, the loop will iterate over any additional properties as well. Check out the example below for a potentially non-intuitive demonstration. + +```js +const arr = [1, 2, 3]; + +Array.prototype.newMethod = true; + +for (const i in arr) { + console.log(i); +} + +// Output: +// 1 +// 2 +// 3 +// newMethod +``` + +It is also worth mentioning that the `for … in` loop is meant for objects, and thus will be slower than other loops which are better suited for arrays. + +### Practical Usage + +So, wait, why use the `for … in` loop at all? + +The `for … in` loop may be most practically used as a tool to debug. It is an easy way to check the properties of an object. + +## 4. while loop +```js +while (condition) { + // do some repetitive task +} +``` + +The `while` loop will evaluate the `condition` before the loop is run each time. If the `condition` evaluates to `true`, the loop executes the statement(s) in the block. Otherwise, the loop exits and stops executing the statement(s) in the block. + +The `while` loop is known as a pre-test loop because it evaluates the `condition` *before* each iteration. The loop will never execute if the condition evaluates to `false` before entering the loop. + +### Example + +```js +let count = 5; +while (count > 0) { + console.log(count); + count -= 1; +} + +// Output: +// 5 +// 4 +// 3 +// 2 +// 1 +``` + +Try converting the following `for-loop` into a `while` loop: +```js +for (int i = 0; i <= 20; i += 5) { + console.log(i); +} +``` + +
+ + Click here to reveal a possible solution + + + ```javascript + let i = 0; + while (i <= 20) { + console.log(i); + i += 5; + } + + // Output: + // 0 + // 5 + // 10 + // 15 + // 20 + ``` +
+ +## 5. do…while loop +```js +do { + // perform repetitive task at least once +} while(condition) +``` + +The `do...while` statement creates a loop that executes a block of code until a condition evaluates to `false`. + +The statements in the block will **always** be executed once before the condition is checked. This is what differentiates a `do...while` loop from a `while` loop. The `do...while` loop is sometimes called a post-test loop. + +### Example +```js +let i = 1 +do { + console.log(i); + i += 1; +} while (i <= 5) + +// Output: +// 1 +// 2 +// 3 +// 4 +// 5 +``` + +### Common Pitfall: Indefinite Loop + +It’s important to ensure the variable(s) used in the statement are updated such that the `while(condition)` evaluates to false. Otherwise, you may crash your program due to an infinite loop. + +Spot the bug below: +```js +let x = 5; +let y = 4; +let sum = 0 +do { + sum = x + y; + console.log(sum); + x = x * x + y = y * y +} while(sum >= 0); +``` + +
+ Click here for an explanation + + The program will run indefinitely because the condition `sum >= 0` will always evaluate to `true`. We can fix this by changing the condition to `sum <= 100` or anything that will eventually evaluate to `false`. +
+ +## 6. Additional Statements +### forEach +```js +myArray.forEach(myFunction(currentValue, index, arr)) +``` + +The `forEach` method calls a function and iterates over the elements of an array, map, or set. + +The syntax for the `forEach` method has multiple parts, some of them being optional: + +- `myArray` is the name of the array through which items you would like to iterate. +- `myFunction` is the name of the function you would like to run for each of the elements in the array. +- `currentValue` an element in the array which is currently being iterated upon. It is the only variable which is required to be passed into the function `myFunction`. This is the variable that will represent each element in the array. +- `index` is an **optional** variable used to indicate the index of the current element in the array which is being iterated upon. +- `arr` is an **optional** variable which is the array of the current elements. + +### Example +```js +let instructors = ["Auberon", "Char", "Claire", "Kyra"]; + +function sayHello(instructor) { + console.log(`Hello, ${instructor}!`); +} + +instructors.forEach(sayHello); + +// Output: +// Hello, Auberon! +// Hello, Char! +// Hello, Claire! +// Hello, Kyra! + +function addHello(instructor, index, arr) { + arr[index] = 'Hello, ' + instructor; +} + +instructors.forEach(addHello); + +console.log(instructors) + +// Output: +// ['Hello, Auberon', 'Hello, Char', 'Hello, Claire', 'Hello, Kyra'] +``` + +### break + +The `break` statement can be used to terminate a loop early, before the condition evaluates to `false` and exits the loop. + +### Example +```js +let arr = [5, 10, 15, 20, 25, 30]; + +for (let i = 0; i < arr.length; i++) { + console.log(arr[i]); + if (arr[i] % 15 == 0) { + break; + } +} + +// Output: +// 5 +// 10 +// 15 +``` + +### continue + +The `continue` statement is used to skip the current iteration and go to the next iteration. + +### Example +```js +let arr = [5, 10, 15, 20, 25, 30]; + +for (let i = 0; i < arr.length; i++) { + if (arr[i] % 15 == 0) { + continue; + } + console.log(arr[i]); +} + +// Output: +// 5 +// 10 +// 20 +// 25 +``` + +## Summary +In this lesson, we have seen the following loops and loop control statements: +* `for-loop` +* `for ... of loop` +* `for ... in loop` +* `while loop` +* `do-while loop` +* `forEach loop` +* `break` +* `continue` \ No newline at end of file From 756e2e95a40a34497169a205cc02e421ae3d450d Mon Sep 17 00:00:00 2001 From: char <110567531+char-adadev@users.noreply.github.com> Date: Thu, 8 Dec 2022 11:54:25 -0800 Subject: [PATCH 2/9] Apply suggestions from code review Co-authored-by: Kyra Patton --- learning-another-language/js-loops.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index b39a18d..74e7b2e 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -49,7 +49,7 @@ for (let i = 1; i <= 5; i++) { if (i == 4) { break; } - console.log(i) + console.log(i); } // Output: @@ -78,7 +78,7 @@ for (let i = 0; i <= arr.length; i++) { When iterating over an array, it is possible to accidentally exceed the bounds of the array. One thing to note about the indices of an array: -- The first element of an array is stored at index 0. This is true for JavaScript as well as most other programming languages. Therefore, the index of the last element of an array is equal to `arr.length - 1`. +- As with most other languages, JavaScript arrays are zero indexed meaning the first element of an array is stored at index 0. Therefore, the index of the last element of an array is equal to `arr.length - 1`. When constructing a `for-loop`, there are a couple ways to handle exceeding the bounds of an array. They both involve altering the conditional statement in the `for-loop` to either: @@ -142,7 +142,7 @@ for (let monster of monsters) { ```js const m = new Map(); m.set(1, "red"); -m.set(2, "black") +m.set(2, "black"); for (let item of m) { console.log(item); @@ -182,7 +182,7 @@ for (let key in movies) { ### Common Pitfall: Unexpected Behavior When Iterating over an Array -While you can use the `for … in` to iterate over an array, it is recommended to use one of the aforementioned for-loops instead. +While we can use the `for … in` to iterate over an array, it is recommended we use one of the aforementioned for-loops instead. The reason for this is because the `for … in` loop iterates over **all** of the enumerable properties in an object, including any that may be inherited. @@ -221,7 +221,7 @@ while (condition) { The `while` loop will evaluate the `condition` before the loop is run each time. If the `condition` evaluates to `true`, the loop executes the statement(s) in the block. Otherwise, the loop exits and stops executing the statement(s) in the block. -The `while` loop is known as a pre-test loop because it evaluates the `condition` *before* each iteration. The loop will never execute if the condition evaluates to `false` before entering the loop. +`While` loops evaluate the `condition` *before* each iteration. The loop will never execute if the condition evaluates to `false` before entering the loop. ### Example @@ -277,7 +277,7 @@ do { The `do...while` statement creates a loop that executes a block of code until a condition evaluates to `false`. -The statements in the block will **always** be executed once before the condition is checked. This is what differentiates a `do...while` loop from a `while` loop. The `do...while` loop is sometimes called a post-test loop. +In contrast to a `while` loop, a `do...while` loop will **always** execute the statements in the block once _before_ the condition is checked. ### Example ```js @@ -297,7 +297,7 @@ do { ### Common Pitfall: Indefinite Loop -It’s important to ensure the variable(s) used in the statement are updated such that the `while(condition)` evaluates to false. Otherwise, you may crash your program due to an infinite loop. +It’s important to ensure the variable(s) used in the condition are updated such that the `while(condition)` evaluates to false. Otherwise, our program may crash due to an infinite loop. Spot the bug below: ```js @@ -307,8 +307,8 @@ let sum = 0 do { sum = x + y; console.log(sum); - x = x * x - y = y * y + x = x * x; + y = y * y; } while(sum >= 0); ``` @@ -356,7 +356,7 @@ function addHello(instructor, index, arr) { instructors.forEach(addHello); -console.log(instructors) +console.log(instructors); // Output: // ['Hello, Auberon', 'Hello, Char', 'Hello, Claire', 'Hello, Kyra'] From f59b9d0acbbc704559ae0a08d3d1efc06e494077 Mon Sep 17 00:00:00 2001 From: char Date: Thu, 8 Dec 2022 12:13:36 -0800 Subject: [PATCH 3/9] update subsection formatting --- learning-another-language/js-loops.md | 51 ++++++++++++++++----------- 1 file changed, 30 insertions(+), 21 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index 74e7b2e..355fd12 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -2,14 +2,20 @@ ### Learning Goals * Understand several different looping mechanisms in JS * By the end of this, you should be able to: - * Iterate over data in a list, set, or map using several different types of loops + * Iterate over data in a list, set, or map using several different types of `for` and `while` loops * Understand how to terminate a loop early or skip a loop iteration using the `break` and `continue` keywords -### What is a loop? +### How JS loops are different than (& similar to) other loops we've seen -Loops are used to perform repeated tasks based on a condition. A condition is a statement which can evaluate to either **true** or **false**. A loop will continue running until the condition returns false. +Javascript has several variations of the basic `for` and `while` loops. The `for` family of loops includes the `for` loop, `for ... of` loop and `for ... in` loop. The `while` family of loops includes both the `while` loop and `do-while` loop. -## 1. `for` loop +These loops work similarly to the loops we have seen in Python, but with syntax and quirks that are particular to Javascript. + +Similar to Python, Javascript also provides flow control statements such as `break` and `continue`. + +## For Loop Family + +### `for` loop ```js for (initialization; condition; finalExpression) { @@ -23,12 +29,12 @@ The `for-loop` consists of three optional expressions, followed by a block of co - **condition** - This expression is checked each time before the loop runs. If it evaluates to true, the code in the loop is executed. If it evaluates to false, the loop stops. If this expression is omitted, it automatically evaluates to true, and the code block is executed. - **finalExpression** - This expression is executed after each iteration of the loop. This is usually used to increment (or increase) a counter, but can also be used to decrement (or decrease) a counter. -### Examples +#### Examples **1. Print integers 1 .. 5** ```js for (let i = 1; i <= 5; i++) { - console.log(i) + console.log(i); } // Output: @@ -58,7 +64,7 @@ for (let i = 1; i <= 5; i++) { // 3 ``` -### Common Pitfall: Exceeding the Bounds of an Array +#### Common Pitfall: Exceeding the Bounds of an Array ```js const arr = [ "foo", "bar", "baz" ]; @@ -109,7 +115,7 @@ for (let i = 0; i <= arr.length - 1; i++) { // baz ``` -## 2.`for … of` loop +### `for … of` loop ```js for (variable of object) { // do something @@ -118,7 +124,7 @@ for (variable of object) { The `for … of` loop can be used to iterate over arrays, sets, and maps. When using the `for … of` loop, there’s no danger of going out of bounds! The loop will go over each item in the iterable object. -### Examples +#### Examples **1. Iterate over items in a list** ```js @@ -153,7 +159,7 @@ for (let item of m) { // [2, black] ``` -## 3. `for … in` loop +### `for … in` loop ```js for (property in object) { // do stuff @@ -180,7 +186,7 @@ for (let key in movies) { // 2010: Toy Story 3 ``` -### Common Pitfall: Unexpected Behavior When Iterating over an Array +#### Common Pitfall: Unexpected Behavior When Iterating over an Array While we can use the `for … in` to iterate over an array, it is recommended we use one of the aforementioned for-loops instead. @@ -206,13 +212,15 @@ for (const i in arr) { It is also worth mentioning that the `for … in` loop is meant for objects, and thus will be slower than other loops which are better suited for arrays. -### Practical Usage +#### Practical Usage So, wait, why use the `for … in` loop at all? The `for … in` loop may be most practically used as a tool to debug. It is an easy way to check the properties of an object. -## 4. while loop +## While Loop Family + +### while loop ```js while (condition) { // do some repetitive task @@ -223,7 +231,7 @@ The `while` loop will evaluate the `condition` before the loop is run each time. `While` loops evaluate the `condition` *before* each iteration. The loop will never execute if the condition evaluates to `false` before entering the loop. -### Example +#### Example ```js let count = 5; @@ -268,7 +276,7 @@ for (int i = 0; i <= 20; i += 5) { ``` -## 5. do…while loop +### do…while loop ```js do { // perform repetitive task at least once @@ -279,7 +287,7 @@ The `do...while` statement creates a loop that executes a block of code until a In contrast to a `while` loop, a `do...while` loop will **always** execute the statements in the block once _before_ the condition is checked. -### Example +#### Example ```js let i = 1 do { @@ -295,7 +303,7 @@ do { // 5 ``` -### Common Pitfall: Indefinite Loop +#### Common Pitfall: Indefinite Loop It’s important to ensure the variable(s) used in the condition are updated such that the `while(condition)` evaluates to false. Otherwise, our program may crash due to an infinite loop. @@ -318,7 +326,8 @@ do { The program will run indefinitely because the condition `sum >= 0` will always evaluate to `true`. We can fix this by changing the condition to `sum <= 100` or anything that will eventually evaluate to `false`. -## 6. Additional Statements +## Additional Statements + ### forEach ```js myArray.forEach(myFunction(currentValue, index, arr)) @@ -334,7 +343,7 @@ The syntax for the `forEach` method has multiple parts, some of them being opti - `index` is an **optional** variable used to indicate the index of the current element in the array which is being iterated upon. - `arr` is an **optional** variable which is the array of the current elements. -### Example +#### Example ```js let instructors = ["Auberon", "Char", "Claire", "Kyra"]; @@ -366,7 +375,7 @@ console.log(instructors); The `break` statement can be used to terminate a loop early, before the condition evaluates to `false` and exits the loop. -### Example +#### Example ```js let arr = [5, 10, 15, 20, 25, 30]; @@ -387,7 +396,7 @@ for (let i = 0; i < arr.length; i++) { The `continue` statement is used to skip the current iteration and go to the next iteration. -### Example +#### Example ```js let arr = [5, 10, 15, 20, 25, 30]; From 10eae555ed294cd91947b614c624d164f2f2e1be Mon Sep 17 00:00:00 2001 From: char Date: Thu, 8 Dec 2022 12:34:14 -0800 Subject: [PATCH 4/9] update for-loop formatting --- learning-another-language/js-loops.md | 53 ++++++++------------------- 1 file changed, 15 insertions(+), 38 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index 355fd12..bc908a6 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -17,52 +17,29 @@ Similar to Python, Javascript also provides flow control statements such as `bre ### `for` loop -```js -for (initialization; condition; finalExpression) { - // do stuff -} -``` - -The `for-loop` consists of three optional expressions, followed by a block of code: - -- **initialization** - This expression runs before the execution of the first loop. The initialization expression is usually used to create a counter. -- **condition** - This expression is checked each time before the loop runs. If it evaluates to true, the code in the loop is executed. If it evaluates to false, the loop stops. If this expression is omitted, it automatically evaluates to true, and the code block is executed. -- **finalExpression** - This expression is executed after each iteration of the loop. This is usually used to increment (or increase) a counter, but can also be used to decrement (or decrease) a counter. - -#### Examples - -**1. Print integers 1 .. 5** ```js for (let i = 1; i <= 5; i++) { console.log(i); } +``` -// Output: -// 1 -// 2 -// 3 -// 4 -// 5 - -// intialization statement: let i = 1 -// condition statement: i <= 5 -// final expression: i++, equivalent to i = i + 1 +When we run our code, we should see this output: +``` +1 +2 +3 +4 +5 ``` -**2. Use a break statement to exit the loop immediately** -```js -for (let i = 1; i <= 5; i++) { - if (i == 4) { - break; - } - console.log(i); -} +|
Piece of Code
| Notes | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `for` | The keyword used to begin the loop | +| `let i = 1` | This expression runs before the execution of the first loop. The initialization expression is usually used to create a counter. | +| `i <= 5` | This expression is checked each time before the loop runs. If it evaluates to true, the code in the loop is executed. If it evaluates to false, the loop stops. If this expression is omitted, it automatically evaluates to true, and the code block is executed. | +| `i++` | This expression is executed after each iteration of the loop. This is usually used to increment (or increase) a counter, but can also be used to decrement (or decrease) a counter. | +| `{ console.log(i) }` | This is the body of the loop. This is the code that is executed. | -// Output: -// 1 -// 2 -// 3 -``` #### Common Pitfall: Exceeding the Bounds of an Array ```js From 0f2f83f8c6eb9721c89f41bb41105ca8912b0bfa Mon Sep 17 00:00:00 2001 From: char Date: Fri, 9 Dec 2022 11:29:37 -0800 Subject: [PATCH 5/9] update for loop fam formatting --- learning-another-language/js-loops.md | 126 ++++++++++++++++---------- 1 file changed, 77 insertions(+), 49 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index bc908a6..2b66f68 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -7,7 +7,9 @@ ### How JS loops are different than (& similar to) other loops we've seen -Javascript has several variations of the basic `for` and `while` loops. The `for` family of loops includes the `for` loop, `for ... of` loop and `for ... in` loop. The `while` family of loops includes both the `while` loop and `do-while` loop. +Javascript has several variations of the basic `for` and `while` loops. + +The `for` family of loops includes the `for` loop, `for ... of` loop and `for ... in` loop. The `while` family of loops includes both the `while` loop and `do-while` loop. These loops work similarly to the loops we have seen in Python, but with syntax and quirks that are particular to Javascript. @@ -38,7 +40,7 @@ When we run our code, we should see this output: | `let i = 1` | This expression runs before the execution of the first loop. The initialization expression is usually used to create a counter. | | `i <= 5` | This expression is checked each time before the loop runs. If it evaluates to true, the code in the loop is executed. If it evaluates to false, the loop stops. If this expression is omitted, it automatically evaluates to true, and the code block is executed. | | `i++` | This expression is executed after each iteration of the loop. This is usually used to increment (or increase) a counter, but can also be used to decrement (or decrease) a counter. | -| `{ console.log(i) }` | This is the body of the loop. This is the code that is executed. | +| `{ console.log(i) }` | This is the body of the loop. This is the code that is executed each time the loop is run. | #### Common Pitfall: Exceeding the Bounds of an Array @@ -48,20 +50,19 @@ const arr = [ "foo", "bar", "baz" ]; for (let i = 0; i <= arr.length; i++) { console.log(arr[i]); } +``` -// Output: -// foo -// bar -// baz -// undefined - -// In the above example, arr.length = 3, -// so accessing arr[3] leads to an undefined element +When the code above is run, we will see this output: +``` +foo +bar +baz +undefined ``` When iterating over an array, it is possible to accidentally exceed the bounds of the array. One thing to note about the indices of an array: -- As with most other languages, JavaScript arrays are zero indexed meaning the first element of an array is stored at index 0. Therefore, the index of the last element of an array is equal to `arr.length - 1`. +- As with most other languages, JavaScript arrays are zero indexed meaning the first element of an array is stored at index 0. Therefore, the index of the last element of an array is equal to `arr.length - 1`. In the code block above, `arr.length` = 3, so accessing `arr[3]` leads to an `undefined` element. When constructing a `for-loop`, there are a couple ways to handle exceeding the bounds of an array. They both involve altering the conditional statement in the `for-loop` to either: @@ -71,39 +72,32 @@ When constructing a `for-loop`, there are a couple ways to handle exceeding the ```js const arr = [ "foo", "bar", "baz" ]; -// Replace the <= with < in the condition statement +// Replace <= with < in the condition statement for (let i = 0; i < arr.length; i++) { console.log(arr[i]); } +``` -// Output: -// foo -// bar -// baz +```js +const arr = [ "foo", "bar", "baz" ]; // Replace arr.length with arr.length - 1 for (let i = 0; i <= arr.length - 1; i++) { console.log(arr[i]); } - -// Output: -// foo -// bar -// baz ``` -### `for … of` loop -```js -for (variable of object) { - // do something -} +Both of the above code blocks will give us the following output: +``` +foo +bar +baz ``` -The `for … of` loop can be used to iterate over arrays, sets, and maps. When using the `for … of` loop, there’s no danger of going out of bounds! The loop will go over each item in the iterable object. +### `for … of` loop -#### Examples +The `for … of` loop can be used to iterate over arrays, sets, and [maps](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) (or dictionaries). When using the `for … of` loop, there’s no danger of going out of bounds! The loop will go over each item in the iterable object. -**1. Iterate over items in a list** ```js const monsters = [ "Michael Myers", @@ -114,26 +108,50 @@ const monsters = [ for (let monster of monsters) { console.log(monster); } +``` -// Output: -// Michael Myers -// Jason Voorhees -// Freddy Krueger +When the code block above is run, we will see this output: ``` +Michael Myers +Jason Voorhees +Freddy Krueger +``` + +|
Piece of Code
| Notes | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `for` | The keyword used to declare the loop. | +| `let monster of monsters` | Assigns the variable `monster` to each item in the array `monsters` as the iteration through the loop occurs. | +| `console.log(monster)` | The block of code executed each time the loop runs. This line logs out the `monster` in the current iteration. | + +### !callout-info -**2. Iterate over items in a map** +#### let vs var vs const + +We use `let` to declare the variable `monster` in the above code block because `let` allows us to block-scope the variable. In contrast, if we were to use `var`, we may inadvertently leak the variable `monster` into a parent scope, which may not be something we necessarily want. Similarly, we would not want to use `const` here as the variable needs to overwrite itself, and we cannot assign the same variable twice. + +If curious, you may learn more about why we want to use `let` for loops in Javascript [here](https://wesbos.com/for-of-es6). + +### !end-callout + +#### Alternative Example + +**Iterate over items in a map** ```js const m = new Map(); m.set(1, "red"); m.set(2, "black"); +m.set(3, "green"); for (let item of m) { console.log(item); } +``` -// Output: -// [1, red] -// [2, black] +We'll get the following output for the code block above: +``` +[1, red] +[2, black] +[3, green] ``` ### `for … in` loop @@ -156,20 +174,28 @@ const movies = { for (let key in movies) { console.log(key + ": " + movies[key]); } +``` -// Ouput: -// 2008: The Dark Knight -// 2009: Avatar -// 2010: Toy Story 3 +The above code block will have the following output: ``` +2008: The Dark Knight +2009: Avatar +2010: Toy Story 3 +``` + +|
Piece of Code
| Notes | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `for` | The keyword used to declare the loop. | +| `let key in movies` | Assigns the variable `key` to each property in the object `movies` as the iteration through the loop occurs. | +| `console.log(...)` | The block of code executed each time the loop runs. This line logs out the object's property key and the resulting value for the property. | #### Common Pitfall: Unexpected Behavior When Iterating over an Array While we can use the `for … in` to iterate over an array, it is recommended we use one of the aforementioned for-loops instead. -The reason for this is because the `for … in` loop iterates over **all** of the enumerable properties in an object, including any that may be inherited. +The reason for this is because the `for … in` loop iterates over **all** of the enumerable properties in an object, including any that may be inherited. This particular loop is not always recommended to use due to the ability to modify object prototypes in JS libraries. Details about prototypes are out of scope for this lesson, but the reader is invited to follow their curiosity, if interested in learning more: [Object Prototypes in Javascript](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes) -If, for instance, a JS library modifies the `Array` prototype, the loop will iterate over any additional properties as well. Check out the example below for a potentially non-intuitive demonstration. +Check out the example below for a potentially non-intuitive demonstration. ```js const arr = [1, 2, 3]; @@ -179,15 +205,17 @@ Array.prototype.newMethod = true; for (const i in arr) { console.log(i); } +``` -// Output: -// 1 -// 2 -// 3 -// newMethod +The above code block will have the following output: +``` +1 +2 +3 +newMethod ``` -It is also worth mentioning that the `for … in` loop is meant for objects, and thus will be slower than other loops which are better suited for arrays. +It is also worth mentioning that the `for … in` loop is meant for _objects_, and thus will be slower than other loops (such as the aforementioned for-loops or the upcoming while loop) which are better suited for arrays. #### Practical Usage From 24eb0c96cb24639960ad501a73e8ed8c441fd6c7 Mon Sep 17 00:00:00 2001 From: char Date: Fri, 9 Dec 2022 12:04:37 -0800 Subject: [PATCH 6/9] update formatting for while loop fam --- learning-another-language/js-loops.md | 81 ++++++++++++++------------- 1 file changed, 41 insertions(+), 40 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index 2b66f68..8dc6f39 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -121,7 +121,7 @@ Freddy Krueger | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `for` | The keyword used to declare the loop. | | `let monster of monsters` | Assigns the variable `monster` to each item in the array `monsters` as the iteration through the loop occurs. | -| `console.log(monster)` | The block of code executed each time the loop runs. This line logs out the `monster` in the current iteration. | +| `{ console.log(monster) }` | The block of code executed each time the loop runs. This line logs out the `monster` in the current iteration. | ### !callout-info @@ -187,7 +187,7 @@ The above code block will have the following output: | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | | `for` | The keyword used to declare the loop. | | `let key in movies` | Assigns the variable `key` to each property in the object `movies` as the iteration through the loop occurs. | -| `console.log(...)` | The block of code executed each time the loop runs. This line logs out the object's property key and the resulting value for the property. | +| `{ console.log(...) }` | The block of code executed each time the loop runs. This line logs out the object's property key and the resulting value for the property. | #### Common Pitfall: Unexpected Behavior When Iterating over an Array @@ -226,33 +226,36 @@ The `for … in` loop may be most practically used as a tool to debug. It is an ## While Loop Family ### while loop -```js -while (condition) { - // do some repetitive task -} -``` - -The `while` loop will evaluate the `condition` before the loop is run each time. If the `condition` evaluates to `true`, the loop executes the statement(s) in the block. Otherwise, the loop exits and stops executing the statement(s) in the block. - -`While` loops evaluate the `condition` *before* each iteration. The loop will never execute if the condition evaluates to `false` before entering the loop. - -#### Example - ```js let count = 5; while (count > 0) { console.log(count); count -= 1; } +``` -// Output: -// 5 -// 4 -// 3 -// 2 -// 1 +The above code block will have the following output: +``` +5 +4 +3 +2 +1 ``` +|
Piece of Code
| Notes | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `while` | The keyword used to declare the `while` loop. | +| `while` | The keyword used to declare the `while` loop. | +| `count > 0` | The condition evaluated each time before the loop is run | +| `console.log(...)` | The block of code executed each time the loop runs. This line logs out the value of `count`. | +| `count -= 1` | Decrements the value of the `count` variable. This is needed to avoid an infinite loop. | + +The `while` loop will evaluate the condition `count > 0` before the loop is run each time. If the condition evaluates to `true`, the loop executes the statement(s) in the block. Otherwise, the loop exits and stops executing the statement(s) in the block. + +`While` loops evaluate the condition *before* each iteration. The loop will never execute if the condition evaluates to `false` before entering the loop. + +#### For practice Try converting the following `for-loop` into a `while` loop: ```js for (int i = 0; i <= 20; i += 5) { @@ -271,43 +274,41 @@ for (int i = 0; i <= 20; i += 5) { console.log(i); i += 5; } - - // Output: - // 0 - // 5 - // 10 - // 15 - // 20 + ``` + The output: + ``` + 0 + 5 + 10 + 15 + 20 ``` ### do…while loop -```js -do { - // perform repetitive task at least once -} while(condition) -``` - The `do...while` statement creates a loop that executes a block of code until a condition evaluates to `false`. In contrast to a `while` loop, a `do...while` loop will **always** execute the statements in the block once _before_ the condition is checked. -#### Example ```js let i = 1 do { console.log(i); i += 1; } while (i <= 5) +``` -// Output: -// 1 -// 2 -// 3 -// 4 -// 5 +The output for the above block of code: +``` +1 +2 +3 +4 +5 ``` + + #### Common Pitfall: Indefinite Loop It’s important to ensure the variable(s) used in the condition are updated such that the `while(condition)` evaluates to false. Otherwise, our program may crash due to an infinite loop. From 37b655c32cd336a4855b259ee944a2c8df34e827 Mon Sep 17 00:00:00 2001 From: char Date: Fri, 9 Dec 2022 12:20:50 -0800 Subject: [PATCH 7/9] update formatting for break/continue --- learning-another-language/js-loops.md | 86 ++++++++++++++------------- 1 file changed, 45 insertions(+), 41 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index 8dc6f39..1e3b370 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -245,11 +245,11 @@ The above code block will have the following output: |
Piece of Code
| Notes | | --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | -| `while` | The keyword used to declare the `while` loop. | +| `let count = 5` | Declares the variable `count`, used to control the logic of how many times the loop is run. | | `while` | The keyword used to declare the `while` loop. | | `count > 0` | The condition evaluated each time before the loop is run | -| `console.log(...)` | The block of code executed each time the loop runs. This line logs out the value of `count`. | -| `count -= 1` | Decrements the value of the `count` variable. This is needed to avoid an infinite loop. | +| `console.log(...)` | The first line in the block of code executed each time the loop runs. This line logs out the value of `count`. | +| `count -= 1` | The second line in the block of code executed each time the loop runs. This line decrements the value of the `count` variable. This line is needed to avoid an infinite loop. | The `while` loop will evaluate the condition `count > 0` before the loop is run each time. If the condition evaluates to `true`, the loop executes the statement(s) in the block. Otherwise, the loop exits and stops executing the statement(s) in the block. @@ -291,7 +291,7 @@ The `do...while` statement creates a loop that executes a block of code until a In contrast to a `while` loop, a `do...while` loop will **always** execute the statements in the block once _before_ the condition is checked. ```js -let i = 1 +let i = 1; do { console.log(i); i += 1; @@ -306,7 +306,13 @@ The output for the above block of code: 4 5 ``` - +|
Piece of Code
| Notes | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `let i = 1` | Declares the variable `i`, which is later used to control the logic of how many times the loop is run. | +| `do` | The keyword used to declare the `do-while` loop. | +| `console.log(i)` | The first line in the block of code executed each time the loop runs. Logs out the value of `i` to the console. | +| `i += 1` | The second line in the block of code executed each time the loop runs. This line increments the value of the `i` variable. This line is needed to avoid an infinite loop. | +| `while (i <= 5)` | This line is the conditional statement. It is used to check whether or not the loop will run again. Once `i` evaluates to a number that is greater than 5, the loop will terminate. | #### Common Pitfall: Indefinite Loop @@ -335,36 +341,11 @@ do { ## Additional Statements ### forEach -```js -myArray.forEach(myFunction(currentValue, index, arr)) -``` - The `forEach` method calls a function and iterates over the elements of an array, map, or set. -The syntax for the `forEach` method has multiple parts, some of them being optional: - -- `myArray` is the name of the array through which items you would like to iterate. -- `myFunction` is the name of the function you would like to run for each of the elements in the array. -- `currentValue` an element in the array which is currently being iterated upon. It is the only variable which is required to be passed into the function `myFunction`. This is the variable that will represent each element in the array. -- `index` is an **optional** variable used to indicate the index of the current element in the array which is being iterated upon. -- `arr` is an **optional** variable which is the array of the current elements. - -#### Example ```js let instructors = ["Auberon", "Char", "Claire", "Kyra"]; -function sayHello(instructor) { - console.log(`Hello, ${instructor}!`); -} - -instructors.forEach(sayHello); - -// Output: -// Hello, Auberon! -// Hello, Char! -// Hello, Claire! -// Hello, Kyra! - function addHello(instructor, index, arr) { arr[index] = 'Hello, ' + instructor; } @@ -372,11 +353,22 @@ function addHello(instructor, index, arr) { instructors.forEach(addHello); console.log(instructors); +``` -// Output: -// ['Hello, Auberon', 'Hello, Char', 'Hello, Claire', 'Hello, Kyra'] +The above code block will have the following output: +``` +['Hello, Auberon', 'Hello, Char', 'Hello, Claire', 'Hello, Kyra'] ``` +|
Piece of Code
| Notes | +| --------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| `function addHello(...)` | The declaration and name of the function which will be executed for each element in our array. | +| `instructor` | The current value in the array being iterated upon. | +| `index` | An **optional** variable used to indicate the index of the current element in the array which is being iterated upon. | +| `arr` | An **optional** variable. It is the array of the current elements. | +| `arr[index] = ...` | This line will be executed for each element in the array. It modifies the element at the `index` by adding 'Hello, ' prior to the value of the variable `instructor`. | +| `instructors.forEach(addHello)` | This line is used to call the function `addHello` on each element in the array `instructors`. | + ### break The `break` statement can be used to terminate a loop early, before the condition evaluates to `false` and exits the loop. @@ -391,11 +383,13 @@ for (let i = 0; i < arr.length; i++) { break; } } +``` -// Output: -// 5 -// 10 -// 15 +The above code block will have the following output: +``` +5 +10 +15 ``` ### continue @@ -412,13 +406,23 @@ for (let i = 0; i < arr.length; i++) { } console.log(arr[i]); } +``` -// Output: -// 5 -// 10 -// 20 -// 25 +The above code block will have the following output: ``` +5 +10 +20 +25 +``` + +### !callout-info + +#### Minimize usage of break and continue + +We often want to minimize the usage of the keywords `break` and `continue` because they can make the execution flow unpredictable or difficult to follow. If possible, it is advised to formulate our loops such that we can avoid over-using them. + +### !end-callout ## Summary In this lesson, we have seen the following loops and loop control statements: From e820bd153632dcfc5d992db27d72e23491fd8762 Mon Sep 17 00:00:00 2001 From: char Date: Fri, 9 Dec 2022 12:26:53 -0800 Subject: [PATCH 8/9] update for in loop formatting --- learning-another-language/js-loops.md | 7 ------- 1 file changed, 7 deletions(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index 1e3b370..af467e8 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -155,15 +155,8 @@ We'll get the following output for the code block above: ``` ### `for … in` loop -```js -for (property in object) { - // do stuff -} -``` - The `for … in` loop iterates over all enumerable properties of an object. The code in the loop is executed for each property in the object. -### Example ```js const movies = { 2008: "The Dark Knight", From 4ac8691579dc22e1fd8a1230cab3629d0a42e7aa Mon Sep 17 00:00:00 2001 From: char Date: Fri, 9 Dec 2022 12:30:50 -0800 Subject: [PATCH 9/9] update wording --- learning-another-language/js-loops.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/learning-another-language/js-loops.md b/learning-another-language/js-loops.md index af467e8..7942ba8 100644 --- a/learning-another-language/js-loops.md +++ b/learning-another-language/js-loops.md @@ -413,7 +413,7 @@ The above code block will have the following output: #### Minimize usage of break and continue -We often want to minimize the usage of the keywords `break` and `continue` because they can make the execution flow unpredictable or difficult to follow. If possible, it is advised to formulate our loops such that we can avoid over-using them. +We often want to minimize the usage of the keywords `break` and `continue` because they can make the execution flow unpredictable or difficult to follow. If possible, it is advised to formulate our loops such that we avoid over-using them. ### !end-callout