Using for…in and if…in Statements in Javascript

Laina Karosic
2 min readMay 25, 2020

--

Photo by Jonas Denil on Unsplash

There are two lesser-used statements and operators in Javascript, the if…in and for…in statements. Let’s dive in to see them in action!

for…in

The for…in statement enumerates over each key in an object. It’s worth noting that this statement will enumerate over keys that are string data types, but will ignore symbol types.

The syntax for for…in, according to MDN, is as follows:

for (variable in object)
statement

I like to think of the for…in statement as “for each key in the object”. This has become my mental-model-mantra.

So for example, if we have an object, person, we could use for..in like so:

let person = {name: “Harry”, age: “35”, location: “NYC”}for(let key in personObj){
console.log(key)
}

And printed to the console we will see…

The result of enumerating over a person object

…all of the keys, or properties, of that object.

if…in

The if…in statement isn’t explicitly designated as it’s own statement according my own research, but rather the in operator exists and the if… statement exists — and using them together brings many lovely options.

The in operator alone will return true if a specified key/property is in an object:

let person = {name: "Harry", age: "35", location: "NYC"}console.log('name' in person)#=> true 

So turning that into a conditional statement with if…in might look like this:

let person = {name: "Harry", age: "35", location: "NYC"}if('age' in person){
console.log(person.age)
}
#=> 35

If these are new to you, try incorporating them into your code and have fun with the options they provide!

Resources

--

--