Reputation: 9592
in
operator seems to be available since forever ago.
var obj = {foo: 'bar'};
if ('foo' in obj) {
console.log(obj.foo);
}
if (undefined !== obj.foo) {
console.log(obj.foo);
}
The two if
blocks in the code above do the same thing. This example itself may be too simple, but by reading MDN, to me, I wouldn't use it. Besides typing less characters and readability, are there any benefits / advantages that I don't see? Can you give me a good example of in
operator usage?
Upvotes: 2
Views: 231
Reputation: 9474
Here's some example that shows a use case for this:
var obj = { foo: undefined }
obj.foo !== undefined; // false
'foo' in obj; // true
When using the in
operator, you test if the property is specified in the given object and not its value.
Upvotes: 2
Reputation: 1878
Using the in operator in javascript we not also can check for a particular property but can iterate over the list.
The ES 5 specification details two distinct syntaxes for the for-in statement:
1.for (var variable in objectExpression) {statement}
2.for (LeftHandSideExpression in objectExpression) {statement}
For Ex.
If i have an Array object like
var objarray=new Array('rakesh','naresh','dinesh','nilesh');
then i can directly loop over the Array Object.
for(var a in objarray)
{
console.log(objarray[a])
};
The output we get is:
rakesh
naresh
dinesh
nilesh
So the 'in' operator has other benefits other than only checking value.
Upvotes: -1
Reputation: 4435
From MDN:
If you set a property to undefined but do not delete it, the
in
operator returns true for that property.
So, the in
operator can be used to find if a property exists in an object, even if it is undefined
. The second way you show, undefined !== obj.foo
, will return false if the property doesn't exist, OR is undefined.
Example:
var obj = { myProp: undefined };
'myProp' in obj; // = true
obj.myProp !== undefined; // false
I can see this being useful if you want to confirm that a property exists on an object before assigning a value to it, since the assignment will work even if the property didn't previously exist.
Upvotes: 2