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.
Member comments are a way for members to communicate, interact, and ask questions about a lesson.
The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io
Be on-Topic
Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.
Avoid meta-discussion
Code Problems?
Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context
Details and Context
Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!