Interview Question 1:
Imagine you have an array in JavaScript. Your task is to loop through this array and display its original properties. How would you approach this task?
Let's break this down. When we see an array, our minds jump to using loops like forEach or map, right?
const myArray = [1, 2, 3, 4, 5, 6]
myArray.forEach((item) => {
console.log(item);
})
Sure, that shows the array stuff, but what about those 'original properties'? Here's the trick: the interviewer isn't after loop skills of yours – it's about how well you get the Prototype concept."
Hmm, what are these original properties and what are the added properties? Well, we know that an Array is also an Object and there is a method through which you can add additional properties to any element i.e with the help of prototype
.
Array.prototype.extraProperty = "coffeeAndJs"
This means every array in JavaScript will now have this property with the value "coffeeAndJs." Let's try looping an array with extraProperty
added.
const myArray = [1, 2, 3, 4, 5, 6]
for(let item in myArray){
console.log(item);
}
Let's see the output:
Something tricky's happening here. Remember that extraProperty
we added? It's showing up with the items in the array. That's the puzzle right there.
Now, the plan(question) is clear: We need to focus on the real properties and ignore those surprise extra properties.
**So yes, we have successfully understood the question.
How to solve it then?**
for(let item in myArray){
if (myArray.hasOwnProperty(item)) {
console.log(item);
}
}
The solution is simple, we just need to add a check.
hasOwnProperty
is a method in JavaScript that's used to check if a specific property exists directly on an object.It ensures that the property you're checking for is not inherited from the object's prototype chain.
So, when you use
myArray.hasOwnProperty(item)
, you're verifying whether the property nameditem
is a direct property ofmyArray
, rather than coming from any prototype it might have.
📍Conclusion:
hasOwnProperty
is a built-in method in JavaScript that allows you to check if a specific property exists directly on an object, rather than being inherited from its prototype chain. This method helps you distinguish between properties that are originally defined on the object itself and properties that come from its prototype.
CREDITS:
This is my first article, if any wrong information or things are not explained in a right manner feel free to give a thoughtful comment and i will rectify it.