How to get the length of an object in JavaScript

To get the length of an object in JavaScript:

  1. Pass the object to the Object.keys() method as a parameter.
  2. The Object.keys() method returns an array of a given object's own enumerable property names.
  3. Use the length property to get the number of elements in that array.

Here is an example:

const user = {
  name: 'John Doe',
  age: 23,
  country: 'United States'
}

const length = Object.keys(user).length

console.log(`Object length is ${length}`)
// Object length is 3

In the above code, we used the Object.keys() method to get an array of the object's keys. The length property of the keys array returns the count of key-value pairs in the object.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.