Use JavaScript's for-in Loop on Objects with Prototypes

Tyler Clark
InstructorTyler Clark
Share this video with your friends

Social Share Links

Send Tweet

Loops can behave differently when objects have chained prototype objects. Let's see the difference we get when we use the for-in loop on an object without a prototype, as opposed to an object with a prototype object.

Instructor: [00:00] Loops give us the power to iterate over items and collections. Some loops work differently depending on the object and its prototype chain.

[00:09] Here, we have an object with two properties -- first name of Tyler and last name of Klerk. Let's try it, let n=0for that property and object, n++, then we'll console.log out n. We'll see that we get two. The for-in loop iterates over innumerable properties of an object.

[00:29] Because our object has two properties, we are going to get a return of two. Now, if we create a new object called proto object, with the property hair of brown, and then we do object.setPrototypeOf(object) to be proto object, we now see that the number of times our for loop has looped over each one of our properties of object is now three.

[00:51] This might be confusing because we did not change the number of properties on our original object. When we set proto object, which has just one property on it, to be the prototype object, our for-in loop steps through the prototype chain object-by-object.

[01:06] Now, instead of our for loop, let's do an if object has own property property, then we will n++. By doing so, we see that our n is now back to two. It has own property method returns a Boole indicating whether the object has the specified property as its own property as opposed to inhering it through the prototype chain.

[01:28] It's also good to know that our for-in loop will only iterate over distinct properties. With our if-check removed, we're back at three. If we change our hair property to be last name, you can see that now we are back to two.