Is it possible to create a non-enumerable property in javascript

It isn’t possible in ECMAScript 3 (which was what the major browsers implemented at the time this question was asked in 2010). However, in ECMAScript 5, which current versions of all major browsers implement, it is possible to set a property as non-enumerable:

var obj = {
   name: "Fred"
};

Object.defineProperty(obj, "age", {
    enumerable: false,
    writable: true
});

obj.age = 75;

/* The following will only log "name=>Fred" */
for (var i in obj) {
   console.log(i + "=>" + obj[i]);
}

This works in current browsers: see http://kangax.github.com/es5-compat-table/ for details of compatibility in older browsers.

Note that the property must also be set writable in the call to Object.defineProperty to allow normal assignments (it’s false by default).

Leave a Comment