How to usehasOwnProperty() in Javascript
The hasOwnProperty()
method is used to check if an object has a specific property as its own property.
Example: Here, objectLength
is incremented for each property encountered during the iteration. After the loop, the total length is then outputted to the console.
Javascript
// Creating an object let myObject = { key1: 'value1' , key2: 'value2' , key3: 'value3' }; // Initializing a counter variable let objectLength = 0; // Iterating through the object using hasOwnProperty() for (let key in myObject) { if (myObject.hasOwnProperty(key)) { objectLength++; } } // Outputting the length of the object console.log( "The length of the object is: " + objectLength); |
Output
The length of the object is: 3
How to Find the Length of JavaScript Dictionary ?
In JavaScript, you may often find a dictionary referred to as an object. Therefore, unlike arrays which have a length property, objects (dictionaries) do not have a built-in length property. However, the “length” of a given dictionary in JavaScript may be determined through counting the pairs of key-value it contains.
Contact Us