Onkar Janwa
Onkar Janwa

Reputation: 3950

"'length' in Object(obj)" How does it work in js?

'length' in Object(obj)

How does the above statement works in JavaScript?

I have found the below JavaScript statement in angular.js lib

var length = 'length' in Object(obj) && obj.length;

Upvotes: 2

Views: 124

Answers (3)

user7110739
user7110739

Reputation:

   var length = Object.keys(myArray).length;

Or

Universal function:-

var objSize = function(obj) {
    var count = 0;
    
    if (typeof obj == "object") {
    
        if (Object.keys) {
            count = Object.keys(obj).length;
        } else if (window._) {
            count = _.keys(obj).length;
        } else if (window.$) {
            count = $.map(obj, function() { return 1; }).length;
        } else {
            for (var key in obj) if (obj.hasOwnProperty(key)) count++;
        }
        
    }
    
    return count;
};

document.write(objSize({ a: 1, b: 2, c: 3 }));

Upvotes: 0

Artur
Artur

Reputation: 628

Object(...) converts primitives to object structure. Examples:

Object(null) // {}
Object(undefined) // {}
Object(10) // Number {[[PrimitiveValue]]: 10}

If you type 'length' in 10 it will throw an error, but 'length' in Object(10) will not (returns false and blocks next statement, which would throw an error if obj has a primitive value).

Your code checks if obj variable is an array or array-like object (has length property).

More about Object and in operator.

Upvotes: 2

Sagar V
Sagar V

Reputation: 12478

That will check whether the property length exists in Object(obj) or not

I guess that is to differentiate between Array and Object.

Because Object doesn't have the property length so it will false for Object.

var a = {
  name: "abc",
  age: "34"
};
var l = 'length' in Object(a) && a.length;
console.log(l);

But array have the property length and it will return the length of the array.

var b = [34, 54, 65];
var ll = 'length' in Object(b) && b.length;
console.log(ll);

When we type checking them, both are same.

var a = [];
var b = {};
console.log(typeof a, typeof b);

There are other methods to differentiate Array and Object too.

Using Array.isArray

var a = [];
var b = {};

console.log(Array.isArray(a));

console.log(Array.isArray(b));

Upvotes: 2

Related Questions