JavaScript — Loops and Iteration

Joanna Brigham
3 min readAug 9, 2021

I’m writing this as for some reason I’m really struggling to get in my head the syntax for loops in JavaScript and the built-in methods for iterating through arrays. I’ve noticed that when I’ve been practicing JavaScript on Codewars this is an area that keeps tripping me up and I’d like to be more fluent in. Though I know I can always consult the documentation, I thought it would be helpful for me to consolidate my knowledge by writing what I’ve learnt in my own words. I’ll also be able to use this as a reference point in future (example code mostly taken from codecademy).

for loop syntax reminder

for (let counter = 0; counter < 4; counter++) {

console.log(counter);

}

Example of how to use a for loop when iterating over an array-

const animals = [‘Grizzly Bear’, ‘Sloth’, ‘Sea Lion’];

for (let i = 0; i < animals.length; i++){

console.log(animals[i]);

}

.forEach()

The forEach iterator executes the same code for each element of an array. It takes a callback function as as argument (function passed as an argument into another function) and executes the callback function for each element of the array. During each execution, the current element is passed as an argument to the callback function. It will do something to each of the values in the array and return undefined. If you want to make changes to the array have to create a new empty array and push elements to it.

There are a few different ways to write them, best to use arrow function but should know about the others-

Arrow function(ES6)-

groceries.forEach(groceryItem => console.log(groceryItem));

Define a function to be used as the callback-

function printGrocery(element){
console.log(element);
}

groceries.forEach(printGrocery);

Function expression -

groceries.ForEach(function(groceryItem){console.log(‘-’ + groceryItem)});

.map()

Map takes an argument of a callback function, the same as forEach, but it returns a new array. Need to remember to always declare a new variable when using .map(). Use map when you want to transform elements in an array.

const numbers = [1, 2, 3, 4, 5];

const bigNumbers = numbers.map(number => {
return number * 10;
});

console.log(numbers); //Output: [1, 2, 3, 4, 5]
console.log(bigNumbers); // Output: [10, 20, 30, 40, 50]

.filter()

Like .map(), it returns a new array, but it can filter out certain elements from the original array, it checks every element in an array to see if it meets certain criteria. The callback function of the .filter() method should return true or false depending on the element passed to it. For elements that return true, they are added to the new array. Use when you want to select multiple elements from an array.

const words = [‘chair’, ‘music’, ‘pillow’, ‘brick’, ‘pen’, ‘door’];

const shortWords = words.filter(word => {
return word.length < 6;
});

console.log(words); // Output: [‘chair’, ‘music’, ‘pillow’, ‘brick’, ‘pen’, ‘door’];
console.log(shortWords); // Output: [‘chair’, ‘music’, ‘brick’, ‘pen’, ‘door’]

.findIndex()

Used to find the location of an element in an array. It returns the index of the first element that evaluates to true in the callback function. If there isn’t an element in the array that evaluates to true, then it will return -1.

const jumbledNums = [123, 25, 78, 5, 9];

const lessThanTen = jumbledNums.findIndex(num => {
return num < 10;
});

console.log(lessThanTen); // Output: 3

console.log(jumbledNums[3]); // Output: 5

.reduce()

Takes an array containing multiple values and returns a single value after iterating through all the elements of an array. For example it can be used to sum all the elements in an array. The callback function has two parameters, in the example below the and currentValue. The value of accumulator starts off as the value of the first element in the array and the currentValue starts as the second element.

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
})

console.log(summedNums) // Output: 17

Can also take an optional second parameter to set an initial value for accumulator.

const numbers = [1, 2, 4, 10];

const summedNums = numbers.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 100) // <- Second argument for .reduce()

console.log(summedNums); // Output: 117

--

--