Shobhit Singh
Shobhit Singh

Reputation: 86

what is use of adding length property to objects in javascript?

Array do support length property as well as string does, but objects don't inherently have a length property.

in case we add a length properly as below.

{"a":0,"b":0,length:2}

what is the use case scenario for above code

Upvotes: 0

Views: 455

Answers (2)

Andrew Bone
Andrew Bone

Reputation: 7291

Here are both methods of getting the length.

You'll notice if you keep track of your own length the display code is a bit shorter but you need a whole function to add a new key, you'd even need another function to remove them.

object.keys changes the keys into an array which we can get the length from this, of course, take a few milliseconds more as it has to do the convert.

I generally run with the assumption a computer is going to make fewer mistakes than me so, if I can, I should load as much work as possible onto it.

// initial set up
let obj1 = {"a":0,"b":0};
let obj2 = {"a":0,"b":0,length:2};

// initial lengths
console.log("obj1: "+Object.keys(obj1).length);
console.log("obj2: "+obj2.length);

// adding standard way
obj1["c"] = 0;

// adding to accomidate with length
function addObj2(key, value) {
  obj2[key] = value;
  obj2.length++;
}
addObj2("c",0);

console.log("--");

// new lengths
console.log("obj1: "+Object.keys(obj1).length);
console.log("obj2: "+obj2.length);

I hope this makes sense.

Upvotes: 0

Federico klez Culloca
Federico klez Culloca

Reputation: 27119

An object doesn't have a length, per se. It depends on what this length represents.

For example, in the code you posted, it's not immediately obvious why the length is 4, but it might make sense in the context of what that object actually represents.

Upvotes: 2

Related Questions