Contenido del Curso
JavaScript Data Structures
JavaScript Data Structures
Method hasOwnProperty()
When iterating through an object's properties using the for...in
loop, it's important to distinguish between the object's own properties and those inherited from its prototype chain.
The hasOwnProperty()
method is a valuable tool for checking whether a property belongs to the object or is inherited from a prototype. Let's explore the hasOwnProperty()
method and how it can safely handle object properties during iteration.
Understanding hasOwnProperty()
The hasOwnProperty()
method is a built-in JavaScript method that allows us to check if a specific property exists directly on an object. It returns a Boolean value (true
or false
) indicating whether the object has a property with the specified name.
Here is the basic syntax of the hasOwnProperty()
method:
object
: The object you want to check;property
: The property name we want to check for.
Using hasOwnProperty() with for...in
Using the for...in
loop, we can combine it with the hasOwnProperty()
method to iterate through an object's properties. It's important to add a check for own properties at each iteration to ensure that we only access the object's own properties. Even if we are certain that the object has no inherited properties, this check will protect against future possible errors.
const exercise = { name: "Deadlift", primaryMusclesWorked: "Erector spinae", equipment: "Barbell", exerciseType: "Strength", difficulty: "Intermediate", }; for (let key in exercise) { if (exercise.hasOwnProperty(key)) { console.log(`Property: ${key}, Value: ${exercise[key]}`); } }
¡Gracias por tus comentarios!