 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- 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
Advertisements
 