JavaScript Demystified

Q. Display the original properties of an array.

This looks like a pretty simple question but it is a bit tricky. Just looping over the array might not give you the correct answer. There is a catch. As it is mentioned to display only the original properties, we should be aware of the fact that there can be new properties added to the array. This leads to the concept of prototype in JavaScript. Prototype helps us to add new properties to the array but those properties won't be considered as original properties. So, the question boils down to printing only the original properties. To print only the original properties, we need to give a check in the loop. If the element satisfies 'hasOwnProperty()' then only we are going to show otherwise we skip it.

Array.prototype.extraProperty = 'Added property'
myArray = [1, 2, 3, 4, 5]
for(let ele in myArray){
    console.log(myArray[ele]) //wrong way
}
// UNDESIRED OUTPUT :
// 1
// 2
// 3
// 4
// 5
// Added property
for(let ele in myArray){
    if(myArray.hasOwnProperty(ele)){ //correct way
        console.log(myArray[ele])
    }
}
//EXPECTED OUTPUT :
// 1
// 2
// 3
// 4
// 5

I learnt this concept from none other than Hitesh Choudhary Sir. He has been posting similar videos on how to crack JS interviews smoothly. A big thanks to you Sir. Expecting more such informative videos.

Video: