/

HTML / CSS / JavaScript Tutorial

JavaScript Operator: in

[this page | pdf | back links]

In JavaScript, the in operator returns true if the specified property is in the specified object, otherwise false. The results can be a little counterintuitive until the exact nature of the object is taken into account:

 

For example, suppose we have an object such as:

 

var x = {name: "ten", val: 10, binaryval: "1010"};

 

Then:

 

y

y in x

Explanation

"name"

true

"name" is a valid property of the object

"val"

true

"val" is a valid property of the object

"length"

true

The object has a length (number of entries)

1

false

An object is not indexed like an array, so there is no entry indexed by 1

 

Suppose, instead, we have an array such as:

 

var x = ["a","b"];

 

Then

 

y

y in x

Explanation

"a"

false

"a" is not a valid property, rather it is the value assigned to the property (the property is the index number)

"length"

true

As arrays do generically have a length property

1

true

As there is an entry with index number 1 (the entry is "b"), although if y were 2 then it would be false (as there is no entry with index number 2)

 


NAVIGATION LINKS
Contents | Prev | Next | JavaScript Operators


Desktop view | Switch to Mobile