"in" operator layman explaination

I am still relatively new to JS, so can someone please explain how the “in” operator functions? I understood that it searches for an index (when given a number) or a string in an object and an array and returns a true/false statement accordingly.

Can someone explain how the “in” operator is working here in the below code? This is a recipe app and the “in” operator is being used to display the list of ingredients as shown, all the data taken from an API.

snip

Screenshot of JS file:

snip2

From what I understand the variable “i” is entering the object and starts searching for the string “strIngredient” using the startsWith( ) function.
Then what is the condition : myMeal[i] doing ?? Is it ensuring that the “in” operator doesn’t go further into the other API objects?

CodePen Link for Recipe App

This is a for...in loop, which is a convenient way to go through all of the properties in an object. The in isn’t really doing anything special, it’s just a keyword used to define the loop. The variable i takes on each property name in the object (myMeal) as you loop through them.

It’s checking if the property in i is in then object myMeal. I think maybe the reason you are questioning it is because it’s not needed. The for...in loop is already looping through the properties in myMeal, so you know that i will always be in myMeal and thus there is no reason to check again.

1 Like

Thank you so much :+1: