Javascript For…In Loops: Pt.2

A Series on JS Loops

Dallas Bille
4 min readJul 15, 2019

Pt 1: “For” Loops

Pt. 3: “For …Of” Loops

Pt.4: “While” Loops

Pt. 5: “Do…While” Loops

A Series On JavaScript Loops

I’m am in the process of doing a series of articles on five useful Javascript Loops (for, for…in, for…of, while, do/while). My goal is to make them easy to understand with examples, and when to use them.

About “for…in” Loops

So now onto the next iteration(get it?) of my series. Hopefully at the end you can loop though all my articles and be more informed than you were before.

“For…In” loops are not so “foreign” (on fire!) to me now. They provide an easy way to loop through objects. And objects are a valuable way to hold data. I am actually surprised I didn’t get more comfortable with this type of loop some time ago.

These loop are great if you are iterating through every element of the object and don’t need to rely on the indexes and such. If you read my regular for loop article you would know this loop requires you to set the index of the loop. For…in does not require this, it just loops through every element, and ends at the last one, or until you find what you’re looking fo. It’s quite easy.

You will need to find your own way to remember which loop (between for…in and for…of) is used for objects, I still get them mixed up.

For…In Loop Structure

This is how the “for…in” loop is structured.

for(key in object){
execute some code
}

Key: This is required. It points to the keys of your object as your iterating. The first of two arguments, you will likely use this in your code block.

Object: Also required. Here you are passing in the object that you’re going to operate on. You will use this in your block.

The structure is much simpler than the “for” loop.

Simple Example

We are going to write a function called findJohn. The goal of this function is to find “John” and return him. We have an object, and one of the values is “John”, so we can just use a “for…in” loop to find “John”.

If you would like to have a better visualization of whats happening. You can paste this into SHELL and run it.

const names = {"not john": "Steven", "still not john": "Walter", "is john": "John", "nope": "Crissy", "nah": "James"}//now we write a function, and use our for loop to return "John", the loop terminates when it finds the first "John".
// remember to get a value from a key we use this syntax names[key].
// Ex. names["nope"] returns "Crissy"
function findJohn(object){
for(key in object){
if(object[key] === "John"){
console.log("We found John!")
return object[key]
} else {
//to visualize the workings, we log all keys that don't point to the value "John"
console.log(key)
}
}
}

If you are having issues sorting this out in your mind, try reading my post about “for” loops, it gives you an understanding on how loops work.

Algorithmic Example:

Because I am currently learning algorithms, I’ll give you a use case of “for…in” with an algorithm.

MaxChars:

Goal: Given a string, return the character that occurs most in that string. These are super fun to try to figure out on your own, so before I show you my solution, try it out!

Suggestion: Type my example in SHELL. Throw console.log()’s as you go so you see the values and get a better understanding of what’s going on.

My Solution:

let string = "we need a harder example"//we need to count how many characters are in the string. We do this by splitting the string, iterating it, and counting the amount of times each one shows up, so we make the keys of our object unique letters, and the values the amount of times the letter occurs.function maxChars(string){//splits string to an array of letters   let splitString = string.split("")//we need to set up a new object, since we are creating one.
let countObject= {}
for(var i = 0; i < splitString.length; i++){
//if the element exists, add 1 to it. If not, make a new //key that is the element, and set its value (count number) to one.
if(countObject[splitString[i]]){
countObject[splitString[i]] += 1
} else {
countObject[splitString[i]] = 1
}
}
//now we can use our for...in loop. We need an empty (character) string to hold the character that occurs the most when we find it. And a counter (most) to keep track of the character with the highest value.
let character = ''
let most = 0
for(var key in countObject){
//The below code is amazing and easy once you wrap your head around it. This blew my mind when I first learned it. // Explained in English: If the count of this letter (countObject[key]) is greater than count of the previous letter, then set "most" variable to that count, then set "character" variable to the letter (key).

if(countObject[key] > most){
most = countObject[key]
character = key
}
}
return character
}
maxChars(string)

I love this algorithmic use of the “for…in” loop. It allows you to practice iterating objects, and dynamically find highest values.

And if everything makes sense, go ride one of these.

Courtesy of Kate Monkey(source)

Resources:

W3Schools

MDN

Udemy Algo Course

--

--

Dallas Bille

Full Stack Web Developer, Adventurer, Soccer Player/Coach