Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
1×
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.

Autoplay

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

    Tyler ClarkTyler Clark
    javascriptJavaScript

    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.

    Code

    Code

    Become a Member to view code

    You must be a Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    Discuss

    Discuss

    Transcript

    Transcript

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

    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.

    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.

    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.

    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.

    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.