Looping is one of the first things you learn as a programmer. It’s not just “for” and “while” loops. You’ve got more options for looping than you’ll probably want to know about.
Let’s take a look.
The classic. Old faithful. If you’re already familiar, feel free to skip ahead.
The basic for-loop’s structure is simple. Repeat a certain amount of code until a condition is met. For a for-loop, that condition is having to run a specific number of times (unless the code itself is designed to exit the loop prematurely).
There are three statements you pass in to a for-loop: the starting point, the end point (exit condition), and the rate at which the loop is going from the start to the end point.
In 99% of cases, the starting point will look like `i = 0`. Why `i`? That’s just what everyone uses. It’s like coding slang. Not a requirement, but it’s familiar. It’s supposed to stand for “integer” since that’s what you’re incrementing.
The second statement, `i < arr.length` means the loop will continue until the value of `i` is greater than the length of `arr` which is the array which was declared before the loop.
The statement is checked before the loop runs. If `i` is greater, the code block won’t run and your loop closes.
The third part, `i++` is shorthand for `i += 1` which is shorthand itself for `i = i + 1`. All it means is you’re iterating `i` by 1. So before the first loop, `i` is equal to 0. Before the second loop, it’s equal to 1.
The third statement runs after your code block has executed.
Put it all together, and our example shows us the for-loop will loop 5 times before moving on.
You can use a basic for-loop to loop a specific number of times, or loop an array, string, or array-like object (by using the `.length` property of whatever it is you’re trying to loop). This is the most versatile configuration and the most-often implemented.
In plain English, this form of looping lets you loop through an object.
To be more precise, I’ll borrow the definition from Mozilla’s web docs: “The `for...in` statement iterates over all enumerable properties of an object that are keyed by strings (ignoring ones keyed by Symbols).”
Let’s look at an example.
Note: the value you name before using the `in` keyword refers to each key. To access the value, you need to call the object with the key (as in the example above).
This syntax looks the same as `for…in` except it works for arrays and strings.
Note: The `forEach()` method works just like this, except only for arrays. If you’re looping an array, use that instead (it’s simpler).
A while-loop is one that re-executes a code block over and over until the exit criteria is met. It’s like a for-loop, except only the third statement.
Let’s say you’re trying to create a program to gamble on blackjack. As long as the cash you have is above zero, you want to run the `playHand()` function.
The `playHand()` function will add or remove from your total cash depending on how well the hand goes. If it’s going well, you want the program to keep playing.
Examples for `while` loops are tough because there aren't many practical use cases. This is one of the first loops you learn, and yet I’ve seen it “in the wild” maybe once. It’s almost always preferable to use a for-loop.
Using a while loop entails a bit of randomness, which is not usually what you want to create as a developer.
Similar to a `while` loop, except you’re guaranteeing the function will run at least once. Instead of the exit criteria being checked before the loop is entered, like on a normal `while` loop, it’s checked at the end.
The method `forEach()` is applied to arrays. It loops through the array as expected and executes a block of code during each iteration.
This example shows a loop through `arr` where each value is logged to the console. Simple.
Computationally, there’s no real advantage to this over crafting a regular for-loop with `arr` like in our very first example at the top of the page, but it sure looks a lot cleaner!
Along with map() below and the basic for-loop, forEach() is the looping approach I see the most in the wild.
Another method, `map()` (not to be confused with `Map` object), looks and works a lot like `forEach()` except you’re actually making an entirely new array.
The new array is created with the results of whatever code is executed each loop.
While it can be used to iterate through an array, `filter()` is kind of in the gray zone. Here, you’re not looping in order to do something to each of the values, nor are you performing an action based on how many times you loop.
Instead, `filter()` is returning a subset of the array you’re passing in based on criteria. Hence the name “filter.”
For example, let’s say we have an array `[1, 2, 3, 4, 5]` and we only want the even values. We can create a new array with only the evens by using filter like this:
You apply the `filter()` method to an array, and pass in a function that returns a boolean. When each value in the array is run through the function, and returns true, that original value is returned as part of the new array.
This would make `newArr` a new array with values `[2,4]`.
You can also abstract out the function and pass in its name to the filter method:
And newArr comes out the same as the original, abstracted arrow function.
Of course, there are many more clever tricks you can use to iterate, manipulate, and search through arrays (e.g. `reduce()`, `values()`, `Object.keys()`, `find()`) but they all require a but more complexity than you typically need.
The loops and methods here are your fundamentals, and will likely make up 99% of all the looping you’ll do.
5 Reasons to Love Databricks
Databricks – a cloud-based, fully-managed, big data processing platform – is the hot new tool our data experts are using to make their lives easier and more productive.
Here are 5 reasons why Databricks is making all the difference:
5 Tools that DevOps Experts Love in 2022
Here at Tensure, we love tools that make our lives in tech easy. Check out the following 5 tools that get our DevOps Engineers raving:
Happy Data Privacy Day! Here are 12 Simple Tips to Keep Your Data Safe
Everything we do online creates data. They can hear us...