0

How is the length of an object calculated?

console.log({0:"a",1:"b"}.length)//returns undefined but object has the length property


Object.hasOwnProperty("length") // true

But how can hasOwnProperty() work?Object dont have this method ,the method is in its prototype

Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41
  • `Object.keys(obj).length` – elclanrs Jun 19 '13 at 10:58
  • 4
    FYI, `Object.hasOwnProperty("length")` returns `true` because `Object` is a **function**, [and functions have a `length` property](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/length). The object you created does not have a `.length` property nor does it inherit one (`Object.prototype.hasOwnProperty('length') === false`). – Felix Kling Jun 19 '13 at 10:59
  • @elclanrs No sir ,i dont want that ,i want to use length property here {}.length – Maizere Pathak.Nepal Jun 19 '13 at 10:59
  • @Felix Kling great thanks ,i was confuse by the name Object and forgot that it is also a function – Maizere Pathak.Nepal Jun 19 '13 at 11:01
  • 2
    @Maizere: `{}` doesn't have a `.length`. `Object` (the constructor) has. Try `console.log({0:"a",1:"b"}.hasOwnProperty("length"))` – Bergi Jun 19 '13 at 11:02

1 Answers1

1

You can use

Object.keys({0:"a",1:"b"}).length;    
Lennart
  • 1,018
  • 1
  • 12
  • 27