JavaScript Loops


I’ve been learning JavaScript on Udemy and did a small loop exercise. The setup is Facebook-like: three users, each with check-in data.

If you enter the right username and password, you see everyone’s check-in feed; if not, you get an error. So I needed a loop to match the login against the user list and check the password.

With the correct account and password, you see something like:

David Lau: Often claims he’s “out on business” when he’s really out eating. His check-in photos live in an album called “It’s All for Life.”

Neil Tzeng: Rarely checks in. During a recent anniversary sale he bought a dishwasher, then spent over a month waiting for someone to install it—once it’s in, he should probably check in.

Micheal Lin: Headhunted by a startup and doing well. Time back in Taiwan is precious and he doesn’t want to be bothered, so he should check in to say he’s not in Taiwan right now.

At first I wanted to use a plain for loop to check names and passwords, but figuring out how to break out once a name matched felt messy, so I switched to a while loop.

Later I looked at the instructor’s approach: he put the for loop inside a function and used return both to send back a value and to exit the loop. A basic but important trick with return.

A quick summary of what I took away about JavaScript loops:

  1. Be careful who you befriend—or you might end up as a coding exercise.
  2. The four common JavaScript loops: for, while, do while, and forEach.
  3. for: the most common; the counter lives right in the parameters.
  4. while: runs until the condition fails; no need to write a counter.
  5. do while: use when you always want to run at least once.
  6. forEach: fastest when you have a list. Its parameter must be a function; the first argument is the list value, the second is the index.
  7. Use functions and return to break out of a loop cleanly.

Facebook loop exercise code:
https://github.com/yellowful/yellowful.github.io/tree/master/fromZeroToMastery/JavaScript/facebook

Other loop practice code:
https://github.com/yellowful/yellowful.github.io/tree/master/fromZeroToMastery/JavaScript/loops