Become a member
to unlock all features

Level Up!

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


    Hide Properties from Showing Up in "for ... in" Loops in JavaScript

    Xiaoru LiXiaoru Li

    Sometimes we need to prevent some properties on a JavaScript object from being iterated over and accessed in "for ... in" loops.

    In this lesson, we will learn how to use Object.defineProperty() to hide existing properties on an object by setting the property descriptor flag enumerable to false.



    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




    Xiaoru Li: Here, we have a simple JavaScript object and a for...in loop. We can hide the property serial number from being accessed in a for...in loop by calling object.defineproperty, then passing our object, the property name, and finally, a property descriptor object with the enumerable flag set to false.

    From now on, this serial number property will stop showing up in for...in loops. This is because the for...in loop only iterates over enumerable properties of an object.