Git Product home page Git Product logo

js-looping-and-iteration-looping-code-along's Introduction

Looping Lab

Objectives

  • Build a for loop.
  • Build a while loop.
  • Explain the purpose of a loop.
  • Understand when to use each type of loop.

Introduction

Sometimes, we need to do things repeatedly. Let's say we have a bunch of gifts to wrap. They all happen to be the same size and shape, so for every gift, we need to cut a similarly sized piece of wrapping paper, fold it up over the edges of the gift, tape it together, and add a nice little card. Then we set the wrapped gift aside and move on to the next gift.

In programming terms, we can think of our collection of gifts as an Array and the act of wrapping them as a function. For example:

const gifts = ["teddy bear", "drone", "doll"];

function wrapGift(gift) {
  // For Ruby or Pythonistas, note that the " is now a ` (back-tick)
  // We'll discuss interpolation in detail elsewhere, but note that
  // JavaScript uses ` like Ruby uses ".
  console.log(`Wrapped ${gift} and added a bow!`);
}

We could then call wrapGift() on each gift individually:

wrapGift(gifts[0]);
wrapGift(gifts[1]);
wrapGift(gifts[2]);

However, this isn't very efficient or extensible. It's a lot of repetitive code to write out, and if we had more gifts we'd have to write a whole new line for each.

This is where loops come in handy! With a loop, we can just write the repeated action once and perform the action on every item in the collection.

Loops are used to execute the same block of code a specified number of times. In JavaScript, loops come in a few different flavors, but the main two are for and while loops.

This is a code-along, so follow along with the instructions in each section. There are tests to make sure you're coding your solutions correctly.

The for loop

Of the loops in JavaScript, the for loop is the most common. The for loop is made up of four statements in the following structure:

for ([initialization]; [condition]; [iteration]) {
  [loop body]
}
  • Initialization
    • Typically used to initialize a counter variable.
  • Condition
    • An expression evaluated before each pass through the loop. If this expression evaluates to true, the statements in the loop body are executed. If the expression evaluates to false, the loop exits.
  • Iteration
    • A statement executed at the end of each iteration. Typically, this will involve incrementing or decrementing a counter, bringing the loop ever closer to completion.
  • Loop body
    • Code that runs on each pass through the loop.

Usage: Use a for loop when you know exactly how many times you want the loop to run (for example, when you have an array of known size).

Examples

The code below will announce our next ten birthdays:

for (let age = 30; age < 40; age++) {
  console.log(`I'm ${age} years old. Happy birthday to me!`);
}

// LOG: I'm 30 years old. Happy birthday to me!
// LOG: I'm 31 years old. Happy birthday to me!
// LOG: I'm 32 years old. Happy birthday to me!
// LOG: I'm 33 years old. Happy birthday to me!
// LOG: I'm 34 years old. Happy birthday to me!
// LOG: I'm 35 years old. Happy birthday to me!
// LOG: I'm 36 years old. Happy birthday to me!
// LOG: I'm 37 years old. Happy birthday to me!
// LOG: I'm 38 years old. Happy birthday to me!
// LOG: I'm 39 years old. Happy birthday to me!

In the above code, let age = 30 is the initialization: we're creating a variable, age, that we'll use in the next three phases of the loop. Notice that we use let instead of const because we need to increment the value of age.

The condition for the above loop is age < 40, or, in other words, "Run the code in the loop body until age is NOT less than 40." As long as the condition evaluates to true, the code in the loop body is executed, the value of age is incremented, and the condition is reevaluated. As soon as the condition evaluates to false, exit the loop.

The iteration is age++, which increments the value of age by 1 after every pass through the loop. We initialized age as 30, and it retains that value during the first pass through the loop. At the end of the first pass, we increment age to 31, check whether the condition still holds true, and, since it does, run the loop body again with age as 31. After that second loop, we increment age to 32, and so on.

The loop body is the set of statements that we want to run when the condition evaluates to true.

The for loop is often used to iterate over every element in an array. Let's rewrite our gift-wrapping action above as a for loop:

const gifts = ["teddy bear", "drone", "doll"];

function wrapGifts(gifts) {
  for (let i = 0; i < gifts.length; i++) {
    console.log(`Wrapped ${gifts[i]} and added a bow!`);
  }

  return gifts;
}

wrapGifts(gifts);
// LOG: Wrapped teddy bear and added a bow!
// LOG: Wrapped drone and added a bow!
// LOG: Wrapped doll and added a bow!
// => ["teddy bear", "drone", "doll"]

We started our counter, i, at 0 because arrays have zero-based indexes. Our condition states that we should run the code in the loop body while i is less than gifts.length (3 in the above example). Our iteration, i++, increments our counter by 1 at the end of each pass through the loop.

In our loop body, notice that we reference gifts[i]. Since i starts out as 0, during the first pass through the loop gifts[i] is gifts[0], which is 'teddy bear'. During the second pass through the loop, gifts[i] is gifts[1], which is 'drone'. And during the final pass through the loop, gifts[i] is gifts[2], which is 'doll'. After the third pass through the loop, we increment i to 3, which is no longer less than gifts.length. Our condition evaluates to false, and we exit the loop.

We'll encounter for loops again when we learn about iterating through object literals.

Assignment

In the previous section, the wrapGift() function allowed us to take any array of gifts and loop over them, logging our own message. Let's practice that with a slightly different idea. To complement our gift wrapping function, your task is to create a thank you card creator.

In index.js, build a function named writeCards() that accepts two arguments: an array of string names, and an event name. Create a for loop with a counter that starts at 0 and increments at the end of each loop. The condition should halt the for loop after the last name in the array is printed out in the loop body.

Inside the loop, create a custom message for each name from the provided array, thanking that person for their gift. Collect the messages in an array and return this array. For example:

writeCards(["Ada", "Brendan", "Ali"], "birthday");

Would produce the following array:

[
  "Thank you, Ada, for the wonderful birthday gift!",
  "Thank you, Brendan, for the wonderful birthday gift!",
  "Thank you, Ali, for the wonderful birthday gift!"
];

The while loop

The while loop is similar to a for loop, repeating an action in a loop based on a condition. Both will continue to loop until that condition evaluates to false. Unlike for, while only requires condition and loop statements:

while ([condition]) {
  [loop body]
}

The initialization and iteration statements of the for loop have not disappeared, though. In fact, we could rewrite our original for loop gift wrapping example using a while loop and achieve the exact same result:

const gifts = ["teddy bear", "drone", "doll"];

function wrapGifts(gifts) {
  let i = 0; // the initialization moves OUTSIDE the body of the loop!
  while (i < gifts.length) {
    console.log(`Wrapped ${gifts[i]} and added a bow!`);
    i++; // the iteration moves INSIDE the body of the loop!
  }

  return gifts;
}

wrapGifts(gifts);
// LOG: Wrapped teddy bear and added a bow!
// LOG: Wrapped drone and added a bow!
// LOG: Wrapped doll and added a bow!
// => ["teddy bear", "drone", "doll"]

Notice that we've just moved the initialization and iteration statements — declaring the i variable outside the loop, and now incrementing it inside the loop.

CAUTION: When using while loops, it is easy to forget to involve iteration. Leaving iteration out can result in a condition that always evaluates to true, causing an infinite loop!

Because of their design, while loops are sometimes used when we want a loop to run an indeterminate number of times. If we were pseudocoding out a program for planting a garden, we could use while to organize the work:

function plantGarden() {
  let keepWorking = true;
  while (keepWorking) {
    chooseSeedLocation();
    plantSeed();
    waterSeed();
    keepWorking = checkForMoreSeeds();
  }
}

We can imagine that while we have seeds, we take the same steps over and over. Choose a location for a seed; plant it; water it. Then, check if there are more seeds. If not, do not keep working.

When to Use for and while

JavaScript, like many programming languages, provides a variety of looping options. Loops like for and while are actually just slight variations of the same process. By providing a variety, we as programmers have a larger vocabulary to work with.

Often, you will see while loops simply being used as an alternative to for loops:

let countup = 0;
while (countup < 10) {
  console.log(countup++);
}

This is perfectly fine as an alternative way to describe:

for (let countup = 0; countup < 10; countup++) {
  console.log(countup);
}

If you're feeling a bit lost about when to use a for vs. a while loop, take a deep breath. Most of the time, a regular for loop will suffice. It's by far the most common looping construct in JavaScript. A general heuristic for choosing which loop to use is to first try a for loop. If that doesn't serve your purposes, then go ahead and try a while or do...while loop. Also, remember that you can always refer to the documentation on these loops at any time.

Just don't forget — with while, make sure you are updating the condition on each loop so that the loop eventually terminates!

Assignment

To get more acquainted with while, your task is to write a function, countDown, that takes in any positive integer and, starting from that number, counts down to zero using console.log(). So, when written if you were to run:

countDown(10);

It would actually log 11 times, including 10:

10
9
8
7
6
5
4
3
2
1
0

Conclusion

After some time programming in JavaScript, writing a for loop will come as naturally to you as wrapping one gift after another. Just as you slowly become comfortable using different words and vocabulary to better express yourself, you will become more acquainted with concepts like for and while until you are able to discern the nuanced differences in usage between them.

Resources

js-looping-and-iteration-looping-code-along's People

Contributors

dependabot[bot] avatar gj avatar ihollander avatar jenmyers avatar lizbur10 avatar maxwellbenton avatar sgharms avatar thuyanduong-flatiron avatar

Stargazers

 avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

js-looping-and-iteration-looping-code-along's Issues

Not Loading

this lab and most of the other JS Labs Won't Load even when i had a fast internet connection please fix this, thank You

Test issue

I am having issues testing the code. I keep getting $ mocha --timeout 5000 -R mocha multi --reporter-options spec=-, json=.results.json

last three tests don't pass

Student Slack discussion says the last three tests in this lab don't work, even the solution branch doesn't pass.

Screen Shot 2019-04-05 at 9 35 54 AM

Problem with running test suite

Does not respond to learn submit in the terminal (so it does not show that I have passed the walkthrough). Also, the test suite doesn't open in the simple server. It opens the last localhost:8000 I had open. . . I've tried quitting and restarting terminal, and it still opens the old lab.

wrong function name in assignment

for the while assignment, it asks to create a function called countDown, but the actual function in the lab is countdown (lowercase "d")

Learn not seeing the lab

The lab page isn't aware of the test, so it does not show that I have passed or failed the lab.

Pull Request not working

I passed all my tests, but my pull request isn't registering, saying the lesson was completed

Using Math.random() >= 0.5 as opposed to Math.random() < 0.5 Is a hard-coded requirement.

I think it should be mentioned in the readme that Using Math.random() >= 0.5 Is a hard-coded requirement. Math.random() < 0.5 on the other hand, hangs the page.

This hangs the page instead of passing or failing the test

const tailsNeverFails = function(){
  let count = 0
  while(Math.random() < 0.5){
    count++
  }
  return `You got ${count} tails in a row!`
}

It works fine in isolation by disabling the tests and running tailsNeverFails() in the console.

I'm not exactly sure this is why, some possibilities are:

  1. Because Math.random is simulated to return a value more than or equal 0.5 the first 2 and 8 times, if I look for the opposite case when it's less than 0.5 (Math.random() < 0.5) Math.random will only be calld once. leaving the page waiting for me to call Math.random 1 or 7 more times.

  2. if math.random is called more then 2 or 8 times it returns 0.2 forever turning my while loop into an infinite loop.

The debugger keeps hanging unpredictable so I'm still not sure where exactly the issue is happening.

Test not picking up presence of Math.random

I think there is an error in the test where it is not taking over for Math.random?

This code is failing when I'm not sure it should:

function tailsNeverFails() {
let number = 0;

while (Math.random() >= 0.5) {
number++;
}
return You got ${number} tails in a row!;
}

formatting typo at 'Loop Body'

Current layout:

  • Iteration

  • A statement executed at the end of each iteration. Typically, this will involve incrementing or decrementing a counter, bringing the loop ever closer to completion. - Loop body

  • Code that runs on each pass through the loop.

Proposed layout:

  • Iteration

  • A statement executed at the end of each iteration. Typically, this will involve incrementing or decrementing a counter, bringing the loop ever closer to completion.

  • Loop body

  • Code that runs on each pass through the loop.

Error: Cannot find module 'jsdom/lib/old-api'

On a fresh copy of this lab, running learn encounters the following error:

  1) "before all" hook:
     Error: Cannot find module 'jsdom/lib/old-api'
      at require (internal/module.js:11:18)
      at Context.<anonymous> (node_modules/mocha-jsdom/index.js:53:5)

Solution for me is the same provided by @ivalentine on another lab here.

Looks like this is a broader issue affecting multiple JS labs. The solution is to change this line in package.json…

"mocha-jsdom": "^1.1.0",

…to this…

"mocha-jsdom": "~1.1.0",

…then run npm install.

Browser alert that Test site is Dangerous

Hey there--when I went to copy and paste the test URL, I was alerted by Chrome that the test site was Dangerous. Not sure if this is useful information, I just wanted to let you know.

Browser alert that Test site is Dangerous (Re-opening)

Hey Kellye, when I ran "learn" in the terminal for this lab, the terminal provided a URL--mine looked something like this: "http://67.205.152.27:41928." When I copy and pasted that into my browser, I got a red warning screen from Chrome saying that the site was dangerous, phishing had been detected, and I shouldn't proceed because my passwords, personal identity, and credit card information could be at risk. I thought I had messed something up, but I reopened the lab and tried the link again and it said the same thing multiple times.

Maybe it was my internet connection, but it was the first time I encountered it working from home (which is common for me) and I had worked on several labs last night, and this was the only lab with which I experienced the issue.

See the image below.

screen shot 2019-02-28 at 7 53 22 pm

Typo: Loop Body <li> bullet

I believe the Loop Body text in the README should be outdented-- it is currently nested under the Iteration bullet point,

Method naming on second assignment.

Hi. The second assignment asks to create a function named "countdown".
Based on naming conventions in earlier material it should be "countDown". Also, it would be nice to make a note on bactick and interpolation just to reinforce it is different that Ruby for the first assignment.
Thanks.

Grammar issue

the iteration move INSIDE the body of the loop

Should be:
the iteration moves INSIDE the body of the loop

When using while loops, it is easy forget to involve iteration

Should be:
When using while loops, it is easy to forget to involve iteration

Sequencing issue

This code-along assumes knowledge about functions that isn't introduced until the "Functions in JavaScript" lesson in the next section.

#staff

Another solution in ES6

Hi.

I noticed that the following code passes the 2nd (while) test in Console, but not through the test.
I get an error message: "ReferenceError: countDown is not defined"

const countDown = (i) => {
while (i >= 0) {
console.log(i);
i--
}
}

Looks like the test is only looking for "countDown()", but you should allow for ES6 syntax as well. Thanks!

Link to Canvas

Add a link to the assignment in Canvas here.

Describe the bug

Write a clear and concise description of what the bug is. Include the file and
line number(s) if possible.

What is the expected behavior?

Write a clear and concise description of what you expected to happen.

Screenshots

If applicable, attach screenshots to help explain your problem.

What OS are you using?

  • OS X
  • WSL
  • Linux

Any additional context?

Add any other context about the problem here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.