- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to get the length of an object in JavaScript?
The length property is only applicable to arrays and strings. So when we call the length property on an object we will get undefined.
Example
<html> <body> <script> var object = {prop:1, prop:2}; document.write(object.length); </script> </body> </html>
Output
undefined
Whereas arrays and strings will display their length when length property is used on them.
Example
<html> <body> <script> var string = 'hello'; var array = [1,2,3]; var len1 = string.length; var len2 = array.length; document.write(len1); document.write("</br>"); document.write(len2); </script> </body> </html>
Output
5 3
In javascript, we have Object.keys() property, which checks whether there are any properties or not. If we use the length property with Object.keys() then the number of properties will be displayed which is nothing but the length of the object.
Example
<html> <body> <script> var object = {one: 1, two:2, three:3}; document.write(Object.keys(object).length); </script> </body> </html>
Output
3
- Related Articles
- How to get the values of an object in JavaScript?
- How to get Property Descriptors of an Object in JavaScript?
- How to get an object containing parameters of current URL in JavaScript?
- How to get the length of a Number in JavaScript?
- How to get the length of a string in JavaScript?
- How to get the length of a string in bytes in JavaScript?
- How to get the size of a json object in JavaScript?
- How to find the length of an array in JavaScript?
- Get the length of a StringBuffer Object in Java
- Filter the properties of an object based on an array and get the filtered object JavaScript
- How to allocate memory to an object whose length is set to 0 - JavaScript?
- Length of a JavaScript object?
- How to get key name when the value contains empty in an object with JavaScript?
- Finding the length of a JavaScript object
- How to get the coordinates of an object in a Tkinter canvas?

Advertisements