What does enumerable mean? - javascript

I was directed to MDN's for..in page when it said, "for..in Iterates over the enumerable properties of an object."
Then I went to the Enumerability and ownership of properties page where it said "Enumerable properties are those which can be iterated by a for..in loop."
The dictionary defines enumerable as countable, but I can't really visualize what that means. Could i get an example of something being enumerable?

An enumerable property is one that can be included in and visited during for..in loops (or a similar iteration of properties, like Object.keys()).
If a property isn't identified as enumerable, the loop will ignore that it's within the object.
var obj = { key: 'val' };
console.log('toString' in obj); // true
console.log(typeof obj.toString); // "function"
for (var key in obj)
console.log(key); // "key"
A property is identified as enumerable or not by its own [[Enumerable]] attribute. You can view this as part of the property's descriptor:
var descriptor = Object.getOwnPropertyDescriptor({ bar: 1 }, 'bar');
console.log(descriptor.enumerable); // true
console.log(descriptor.value); // 1
console.log(descriptor);
// { value: 1, writable: true, enumerable: true, configurable: true }
A for..in loop then iterates through the object's property names.
var foo = { bar: 1, baz: 2};
for (var prop in foo)
console.log(prop); // outputs 'bar' and 'baz'
But, only evaluates its statement – console.log(prop); in this case – for those properties whose [[Enumerable]] attribute is true.
This condition is in place because objects have many more properties, especially from inheritance:
console.log(Object.getOwnPropertyNames(Object.prototype));
// ["constructor", "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", /* etc. */]
Each of these properties still exists on the object:
console.log('constructor' in foo); // true
console.log('toString' in foo); // true
// etc.
But, they're skipped by the for..in loop because they aren't enumerable.
var descriptor = Object.getOwnPropertyDescriptor(Object.prototype, 'constructor');
console.log(descriptor.enumerable); // false

If you create an object via myObj = {foo: 'bar'} or something thereabouts, all properties are enumerable. So the easier question to ask is, what's not enumerable? Certain objects have some non-enumerable properties, for example if you call Object.getOwnPropertyNames([]) (which returns an array of all properties, enumerable or not, on []), it will return ['length'], which includes the non-enumerable property of an array, 'length'.
You can make your own non-enumerable properties by calling Object.defineProperty:
var person = { age: 18 };
Object.defineProperty(person, 'name', { value: 'Joshua', enumerable: false });
person.name; // 'Joshua'
for (prop in person) {
console.log(prop);
}; // 'age'
This example borrows heavily from Non-enumerable properties in JavaScript, but shows an object being enumerated over. Properties can either be or not be writable, configurable, or enumerable. John Resig discusses this in the scope of ECMAScript 5 Objects and Properties.
And, there's a Stack Overflow question about why you'd ever want to make properties non-enumerable.

It's a lot more boring than something that should be visualized.
There is literally an attribute on all properties called "enumerable." When it is set to false the for..in method will skip that property, pretend it doesn't exist.
There are a lot of properties on objects that have "enumerable" set to false, like "valueOf" and "hasOwnProperty," because it's presumed you don't want the JavaScript engine iterating over those.
You can create your own non-enumerable properties using the Object.defineProperty method:
var car = {
make: 'Honda',
model: 'Civic',
year: '2008',
condition: 'bad',
mileage: 36000
};
Object.defineProperty(car, 'mySecretAboutTheCar', {
value: 'cat pee in back seat',
enumerable: false
});
Now, the fact that there is even a secret about the car is hidden. Of course they can still access the property directly and get the answer:
console.log(car.mySecretAboutTheCar); // prints 'cat pee in back seat'
But, they would have to know that the property exists first, because if they're trying to access it through for..in or Object.keys it will remain completely secret:
console.log(Object.keys(car)); //prints ['make', 'model', 'year', 'condition', 'mileage']
They should have just called it, "forInAble."

I will write one line definition of ENUMERABLE
Enumerable: Specifies whether the property can be returned in a for/in loop.
var obj = {};
Object.defineProperties(obj, {
set1: {enumerable: true},
set2: {enumerable: false},
});
Object.keys(obj); // ["set1"]
Object.getOwnPropertyNames(obj); // ["set1", "set2"]

If you're having difficulty visualising "what does it mean to be enumerable?" why not ask yourself, what does it mean to be nonenumerable?
I think of it a bit like this, a nonenumerable property exists but is partially hidden; meaning that nonenumerable is the weird one. Now you can imagine enumerable as what is left - the more natural property we're used to encountering since we discovered Objects. Consider
var o = {};
o['foo'] = 0; // enumerable, normal
Object.defineProperty(o, 'bar', {value: 1}); // nonenumerable, weird
Now in a for..in, imagine it like pseudocode
for property in o:
if not property enumerable continue // skip non-enumerable, "bar"
else do /* whatever */ // act upon enumerable, "foo"
where the body of the loop you typed in JavaScript is in the place of /* whatever */

Built-in methods that objects inherit are not
enumerable, but the properties that your code adds to objects are enumerable unless explicitly stated

Think of the enum data type, just a structure of objects that correspond to different numbers. To declare something to as an enumerable is to declare that it corresponds to a specific number, allowing it to be given a place in a Dictionary that represents countable components of an object. To put it simply, making an object enumerable is the same as telling the compiler, "Hey, this property counts, I want to see this when I check for data on this object."

methods are not enumerable; or rather built in methods are not.. tho after searching on what enumerable means to java script; it just refers to a property attribute.. all created objects in ecma3 are enumerable, and ecma5 u can now define it....that's it.. :D lol took me a bit to find the answer; but I believe its talked about in David Flanagan's book.. so I guess it means "hidden", or not "hidden" in that methods are not shown in the for in loop, and thus are "hidden"

Related

In Javascript, "for...in" doesn't iterate over properties of prototype?

On MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty), I saw snippet like this:
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
}
else {
console.log(name); // toString or something else
}
}
In the snippet, console.log(name); // toString or something else looks a bit confusing to me. I understand toString is a property of Object.prototype and this property can be accessed by buz.toString.
However, when I run the snippet in Chrome, I didn't saw the toString property is printed (console.log), though the comments say it should be iterated by for..in and printed..
Does anyone have ideas about why the properties from one's prototype can't be iterated by "for..in"?
for x in obj iterates over only enumerable properties of the object (including those on the prototype). A given property can be marked as enumerable or not. So, if for/in is skipping some property, then that is likely because that property is not configured as enumerable.
See working demo here: http://jsfiddle.net/jfriend00/gyc9gnmj/ that shows how only enumerable properties are iterated with for x in obj.
And, in fact, you can see that the toString() method is marked as enumerable: false with this code:
function log(x) {
document.write(JSON.stringify(x));
}
var buz = {
fog: 'stack'
};
log(Object.getOwnPropertyDescriptor(Object.getPrototypeOf(buz), "toString"));
Just to shed more light in continuation with what jfriend00 has already answered, Object's data properties in JavaScript has four attributes namely [[configurable]], [[enumerable]], [[writable]] and [[value]] all of which is set to for the former three the default value is true and for the last it defaults to undefined.
Say suppose there exists a need where you would like to avoid a property's value not to be returned in a for-in loop. You can write as
var car = {};
Object.defineProperty(car, 'name',{
enumerable : false,
value : 'BMW'
});

hasOwnProperty when to use, and when not needed?

It is recommended to always use hasOwnProperty, but in many cases this is not needed.
For example consider the following code:
var object = JSON.parse(somejsontext);
for(var prop in object) {
console.log(object[prop]);
}
I know in this case that prop is part of the object, it is explict define by the for..in.
But according to MOZ https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty we should use it to avoid iterating over non-enumarable props, with this example:
var buz = {
fog: 'stack'
};
for (var name in buz) {
if (buz.hasOwnProperty(name)) {
console.log('this is fog (' + name + ') for sure. Value: ' + buz[name]);
}
else {
console.log(name); // toString or something else
}
}
But testing this code actually, never goes to the else.
So when does make sense the use of hasOwnProperty ?
UPDATE: Considering the choosen answer, we can safetly avoid the use of hasOwnProperty in this cases:
- Object js has not been extended by any javascript library or by our code
- Object is a simple code that we have control on
The problem arises when a prototype includes enumerable properties that your code did not anticipate. For example, suppose this ran just before your example:
Object.prototype.foobar = "hello";
In this case, iterating over buz would include the enumerable foobar prototype property. This hasOwnProperty pattern allows your code to differentiate between properties that are directly on the object, versus properties that are inherited from a prototypal ancestor.
The problem is not "enumerating over non-enumerable properties" (that's by definition not possible, unless you explicitly get them via getOwnPropertyNames for each level of the prototype hierarchy), but rather enumerating over inherited properties. This is a concern when using libraries that may add enumerable properties to high-level prototypes, exactly as I have illustrated above.
If you want to add a property to a prototype without causing that property to be enumerated, you can make a non-enumerable property with Object.defineProperty:
Object.defineProperty(Object.prototype, "foobar", {
value: "hello",
enumerable: false,
writeable: true,
configurable: true
});
Such a property would not appear in a for..in loop on buz (or in a for..in loop directly on Object.prototype, either).

Access to internal object fields in Js

Having this code
var a = {date : 12};
for(var t in a){
alert(t);
}
I have one alert with date property.
But everywhere (i.e. here) i see that it is needed to write :
for (var property in object) {
if (object.hasOwnProperty(property)) {
// do stuff
}
}
So why i don't see internal properties of object?
The for..in syntax iterates every property of the object, including those found on the prototype chain (if they are enumerable). This is usually not what you want, so the hasOwnProperty check is usually recommended.
In your case it's not necessary, as your plain object doesn't inherit any enumerable properties from the Object prototype (the only thing in its prototype chain)
Also, for..in gives you the property names (keys) of the object, if you're interested in the value of that particular property, you have to use the bracket notation, extending your example to this:
var a = {date : 12};
for(var t in a){
alert(a[t]);
}
In JavaScript there exists the 'prototype chain', a form of inheritance. If you were to add a property to the prototype of a, and then add your date property directly onto a, your for loop would find both those properties.
The hasOwnProperty checks whether the current property has been attached directly to the context object or whether it has been inherited through the prototype chain.
So in my example, if you had added a property to a's prototype, the hasOwnProperty condition would return false and you wouldn't "do stuff" with it.
I guess the best way to see it is through an example:
Object.prototype.aBaseProperty = 123;
var childObject = { date: 12 };
for (var property in childObject) {
console.log(property)
}
// output: date aBaseProperty
for (var property in childObject) {
if (childObject.hasOwnProperty(property)) {
console.log(property)
}
}
// output: date
Also, rather than doing the hasOwnProperty check, you might prefer
Object.keys(object).forEach(function(value, key) { ... });
Where Object.keys will only return own properties.

Two ways of determining if object has property in JavaScript

Given this object:
var myObject = {
...
};
Is this method:
var hasProp = Object.keys(myObject).indexOf('myProp') !== -1;
The same as:
var hasProp = myObject.hasOwnProperty('myProp')
That is, will they result in the same value for hasProp, always?
I was asked this in an interview and the interviewer said they would yield different results but did not give me an example.
Thanks!
Any non-enumerable property breaks this symmetry. For example, fire up a Node.js console or use a compliant browser's console to perform both:
Object.keys([]); // yields []
[].hasOwnProperty('length'); // yields true.
because for arrays, the magic length property is marked as non-enumerable. There is another function which does all of them, even non-enumerables:
Object.getOwnPropertyNames([]) // yields [ 'length' ]
that is fully equivalent.
Object.keys "returns an array of a given object's own enumerable properties". hasOwnProperty works regardless of the fact that the property is enumerable or not.
See this example where hasOwnProperty is true yet Object.keys does not contain the property.
var obj = {};
Object.defineProperty(obj, "prop", {value: 1, enumerable: false});
obj.prop; // 1
obj.hasOwnProperty("prop"); // true
Object.keys(obj); // []
Object.keys(obj).indexOf('prop'); // -1
This uses the ECMAScript 5 defineProperty but non-enumerable properties also exist on basic objects. As shown by #ChrisDrost, the array's length is a non-enumerable property that does not show up in Object.keys yet responds true to hasOwnProperty.
Your code will not always return the same value for hasOwnProperty.
From Mozilla's Documentation on hasOwnProperty:
Example: Direct versus inherited properties
The following example differentiates between direct properties and
properties inherited through the prototype chain:
o = new Object(); o.prop = 'exists'; o.hasOwnProperty('prop'); // returns true
o.hasOwnProperty('toString'); // returns false
o.hasOwnProperty('hasOwnProperty'); // returns false
Which means that your method acts as a sort of hasOwnProperty that also checks for inherited attributes.
I think in practice, they act the same, but this a subtle difference.

Array index as property

How can you prove that an array’s indices are just the enumerable properties? I know, it shows up during a for in loop, but what I mean is: how can I prove that an array’s index is a property? And also an enumerable property?
Are they identical to general Object properties?
You can prove it’s an enumerable property pretty easily. As you said, it shows up in a for in loop. That’s the definition of “enumerable”. If you want another way, though:
var a = ['hello'];
Object.getOwnPropertyDescriptor(a, '0')
// {value: 1, writable: true, enumerable: true, configurable: true}
And yes, they’re like any other object property, except for that they change an array’s length if one past the end is created. That’s the only different thing about arrays.
var a = [];
a[0] = 5;
a.length // 1
Assuming I've understood your question correctly, yes, array indices are effectively the same as object properties. When you set the property of an object, the internal [[DefineOwnProperty]] function runs. The specification gives a modified version of that function that is used when dealing with Array objects.
After various checks (to ensure the property identifier is a valid array index for example), it does the following:
5. Return the result of calling the default [[DefineOwnProperty]] internal method (8.12.9) on A passing P, Desc, and Throw as arguments
Which is exactly what happens for "normal" objects.

Categories

Resources