Raj
Raj

Reputation: 3061

What does an expression like “[literal] in [array/object]” mean?

What does the following syntax mean:

1 in [1,2,3,5]

I know it doesn't search for the element with the value “1” in the array. But what does it do?

I've seen it used in loops:

for (var i in testArray)
{
   
}

But have also seen this used by itself. Does it mean check if the literal is a valid index in the array or object that is the other operand?

Upvotes: 1

Views: 297

Answers (5)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385144

Very simply, it's an object property search:

console.log('a' in {'a':1, 'b': 2}); // true
console.log('c' in {'a':1, 'b': 2}); // false

Live demo.

This is subtly different to the similar use of in in for loops.


Also note that it should not be used with arrays, although this is a common error to make.

It is unspecified what properties besides numeric keys make up the internals of an array, so you should stick to the Array API (e.g. indexOf) if you're using Arrays, otherwise you'll end up with behaviour that you may not expect:

console.log('length' in [1,2,3,4]); // true

Upvotes: 3

CountZero
CountZero

Reputation: 2882

'in' operator returns true if specified property exists in specified object; used in a loop it allows you to iterate over all properties of the object

Upvotes: 1

Rob W
Rob W

Reputation: 348992

literalinobject means: "Get a property literal from object."

When used in a loop, the engine will try to access all properties of the object.

1 in [1,2,3,4] doesn't check for an occurence of an element with a value of 1, but it checks whether element 1 (array[1]) exists or not.

Upvotes: 2

Shadow Wizard
Shadow Wizard

Reputation: 66389

It's used to iterate JavaScript objects.

This loop will iterate through each "key" in the object.

Its common usage is iterate through such objects:

var Car = { color: "blue", price: 20000 };
for (var key in Car)
    console.log("Propery " + key + " of Car is: " + Car[key]);

Live test case - check Chrome/Firefox JavaScript console to see the output.

When used for plain arrays, each "key" will be the index.. for example:

var nums = [20, 15, 30]
for (var key in nums)
    console.log("Propery " + key + " of array is: " + nums[key]);

Will show the keys as 0, 1 and 2. Updated fiddle for such case.

Upvotes: 1

Daniel A. White
Daniel A. White

Reputation: 190945

It looks like a cheap way not to use a traditional for loop for each item in the array.

Your 2nd example is a for-each loop. It doesn't have the literal 1 (one).

Upvotes: 1

Related Questions