Earlier this week, during one of my code challenges, I was asked to create a function that took in two arguments, an object and a property, that would return the value of the prop if the object contained the property or simply false if it didn't. Long story short, I ended up using Javascript's hasOwnProperty , but along the way I came across / dove into the in operator.
As someone who has never really used [for .. in loops](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) in Javascript, I never had the chance to really dive into what the in operator is actually doing / used for, until recently.
What Does the In Operator Look Like?
let object = {fruit: "apple", job: "lawyer"}
// propertyName in objectWeWantToCheck
"fruit" in object
What Does the In Operator Do?
It returns true if the object OR its prototype chain contains the specified property
So using our example above: it would result in true
How To Use It
With Arrays
// Use the index of the array + in operator + array name
let colors = ["red","green","blue"]
0 in colors // true
1 in colors // true
3 in colors // false
9 in colors // false
// Notice that the operator functions differently with arrays than it does with objects
// You must use the index with arrays, not the value
"red" in colors // false
// Arrays have a .length property that tells us ... the length, we can use in to confirm this
"length" in colors // true
With Objects
let object = {fruit: "apple", job: "lawyer"}
"fruit" in object // true
"height" in object // false
Alongside the Delete operator and Undefined Properties
let object = {fruit: "apple", job: "lawyer"}
delete object.fruit
"fruit" in object // false
// However -- if instead we did the following:
let object = {fruit: "apple", job: "lawyer"}
object.fruit = undefined
// We'd be in for a surprise
"fruit" in object // true
Its always nice to notice and pick up on little things like this as you continue to grow as a developer 😎
Top comments (1)
Well, I too didn't know about the in operator... Thanks