Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
Finding the length of a JavaScript object helps developers know how many properties an object has. Unlike arrays, objects do not have a direct length property. To count the properties, we can use methods like Object.keys(), Object.values(), or Object.entries(). These methods convert the object into an array, making it easy to count the items. This method is useful when working with data from APIs, filtering information, or managing large datasets.
In this article, you will learn simple ways to find the length of a JavaScript object, understand its syntax, and see how to use it in real-world coding.
1. Using the Object.keys() Method
`Object.keys()` returns an array of all the enumerable property names of an object. You can then loop through this array to access each property.
1. `Object.keys(student)` returns an array of keys: `["name", "age", "course"]`.
2. `keys.length` gives the number of properties in the object, which is 3 in this case.
3. The `forEach` loop iterates through the array of keys & logs each key-value pair.
4. The output will be:
Number of properties: 3
name: John
age: 21
course: Computer Science
This method is more flexible because it allows you to work with the array of keys directly, making it easier to count properties or perform other operations.
2. Using for-in Loop and hasOwnProperty() Method
The `for...in` loop is a simple way to iterate over all the enumerable properties of an object. Here’s how it works:
1. We define an object `student` with three properties: `name`, `age`, & `course`.
2. The `for...in` loop iterates over each property in the object.
3. Inside the loop, `key` represents the property name (e.g., `name`, `age`), & `student[key]` gives the corresponding value.
4. The output will be:
name: John
age: 21
course: Computer Science
This method is simple but has a limitation: it only loops through enumerable properties. If you want to include non-enumerable properties, you’ll need a different approach.
To ensure only an object's own properties are counted (excluding inherited properties), we use the hasOwnProperty() method.
Example
const student = {
name: "John",
age: 22,
course: "Computer Science"
};
let count = 0;
for (let key in student) {
if (student.hasOwnProperty(key)) {
count++;
}
}
console.log(count);
You can also try this code with Online Javascript Compiler
The length property of this array gives the number of properties (3).
5. Get Length of Object Using for...in Loop
We can also use a for...in loop without hasOwnProperty() to count properties. This method is simple but may count inherited properties if not used carefully.
Example
const student = {
name: "John",
age: 22,
course: "Computer Science"
};
let count = 0;
for (let key in student) {
count++;
}
console.log(count);
You can also try this code with Online Javascript Compiler
This approach may include inherited properties if the object is part of a prototype chain.
How to Loop through All the Fields of the Object & Check Their Property
When working with objects in JavaScript, you often need to loop through all their fields (properties) to perform certain operations. This is especially useful when you want to count the number of properties in an object, which indirectly helps you determine its length.
To loop through an object’s fields, you can use methods like `for...in` or combine `Object.keys()` with a loop.
Checking Property Types
While looping through object properties, you might also want to check their types. For example, you can determine if a property is a function, object, or primitive value.
const student = {
name: "John",
age: 21,
course: "Computer Science",
greet: function() {
console.log("Hello!");
}
};
for (let key in student) {
if (typeof student[key] === 'function') {
console.log(key + " is a function.");
} else {
console.log(key + " is a " + typeof student[key]);
}
}
You can also try this code with Online Java Compiler
1. The `typeof` operator checks the type of each property value.
2. If the value is a function, it logs that the property is a function. Otherwise, it logs the type of the value.
3. The output will be:
name is a string
age is a number
course is a string
greet is a function.
This approach helps you understand the structure of an object better, especially when dealing with complex objects.
Object.keys vs Object.getOwnPropertyNames
Parameters
Object.keys()
Object.getOwnPropertyNames()
Enumerable Properties
Returns an array containing only the enumerable properties of an object, which are the properties that appear when using a for...in loop.
Returns an array containing all properties of an object (both enumerable and non-enumerable), providing a complete list of the object's direct properties.
Symbol Properties
Does not include properties that use Symbol as their key, even if they are enumerable.
Does not include Symbol properties in the returned array. To get Symbol properties, use Object.getOwnPropertySymbols().
Inherited Properties
Only returns the object's own enumerable properties and excludes properties inherited from the prototype chain.
Only returns the object's own properties (including non-enumerable ones) and excludes properties inherited from the prototype chain.
Common Use Cases
Used when iterating over an object's regular enumerable properties, such as when working with plain objects or performing data transformations.
Used when accessing all properties of an object, including hidden or non-enumerable properties, which is useful for debugging or inspection.
Performance
Generally performs faster since it only checks for enumerable properties.
May have slightly lower performance since it checks for all properties, but the difference is usually negligible.
Property Descriptors
Only considers the enumerable flag of property descriptors when determining which properties to return.
Ignores the enumerable flag and returns all properties regardless of their property descriptor settings.
Object Length with Symbols
In JavaScript, objects can have properties keyed by Symbols, which are unique and immutable primitive values. Symbols are often used to add properties to objects without the risk of naming conflicts. However, when calculating the length of an object, Symbols are not included in methods like `Object.keys()` or `Object.getOwnPropertyNames()`. To handle Symbol properties, JavaScript provides a specific method called `Object.getOwnPropertySymbols()`.
Let’s discuss how Symbols affect object length and how to work with them.
What are Symbol Properties?
Symbols are unique identifiers that can be used as property keys. They are created using the `Symbol()` function.
Example:
const id = Symbol('id'); // Creating a Symbol
const student = {
name: "John",
age: 21,
[id]: 12345 // Using the Symbol as a property key
};
console.log(student);
You can also try this code with Online Javascript Compiler
1. We create two Symbols, `id` and `grade`, and use them as property keys in the `student` object.
2. `Object.getOwnPropertySymbols(student)` returns an array of all Symbol properties in the object.
3. The output is `[Symbol(id), Symbol(grade)]`.
Calculating Object Length with Symbols
To calculate the total length of an object, including both regular properties and Symbol properties, you can combine `Object.keys()`, `Object.getOwnPropertyNames()`, and `Object.getOwnPropertySymbols()`.
Example:
const id = Symbol('id');
const grade = Symbol('grade');
const student = {
name: "John",
age: 21,
[id]: 12345,
[grade]: 'A'
};
// Get all property names (enumerable & non-enumerable)
const propertyNames = Object.getOwnPropertyNames(student);
// Get all Symbol properties
const symbolProperties = Object.getOwnPropertySymbols(student);
// Calculate total length
const totalLength = propertyNames.length + symbolProperties.length;
console.log("Total length of the object: " + totalLength);
You can also try this code with Online Javascript Compiler
3. The total length is calculated by adding the lengths of both arrays, resulting in `4`.
Practical Use Case
Symbols are often used to add metadata or hidden properties to objects without interfering with regular property names. For example, you might use Symbols to store internal state or configuration data.
Example:
const debugMode = Symbol('debugMode');
const settings = {
theme: "dark",
fontSize: 14,
[debugMode]: true
};
if (settings[debugMode]) {
console.log("Debug mode is enabled.");
} else {
console.log("Debug mode is disabled.");
}
You can also try this code with Online Javascript Compiler
1. A Symbol `debugMode` is used to store a hidden property in the `settings` object.
2. The property is accessed using `settings[debugMode]`.
3. Since `debugMode` is a Symbol, it won’t conflict with other property names like `theme` or `fontSize`.
Frequently Asked Questions
What is the easiest way to get the length of an object in JavaScript?
The simplest way is using Object.keys(object).length, as it directly returns the number of properties.
Why doesn't JavaScript provide a built-in length property for objects?
Objects in JavaScript are designed as collections of key-value pairs, not indexed lists like arrays. Since properties can be dynamically added or removed, a built-in length property could become unreliable.
Which method is best for getting the length of an object?
If you only need to count properties, Object.keys(object).length is the most efficient. If you also need key-value pairs, Object.entries(object).length works well.
Conclusion
In this article, we learned different ways to find the length of a JavaScript object. We discussed methods like using Object.keys(), Object.values(), and Object.entries() to determine the number of properties in an object. Understanding these approaches helps developers efficiently manage and manipulate objects in JavaScript, ensuring better data handling in web applications.
Live masterclass
Microsoft SDE Roadmap: Use AI Tools to Succeed
by Pranav Malik
19 May, 2025
01:30 PM
Break into MAANG Data Analyst roles from Non-Tech Profession
by Abhishek Soni
20 May, 2025
01:30 PM
SDE LinkedIn & Naukri Hacks to Get More Recruiter Calls
by Shantanu Shubham
21 May, 2025
01:30 PM
Amazon Data Analyst: Advanced Excel & AI Interview Tips
by Megna Roy
22 May, 2025
01:30 PM
Microsoft SDE Roadmap: Use AI Tools to Succeed
by Pranav Malik
19 May, 2025
01:30 PM
Break into MAANG Data Analyst roles from Non-Tech Profession