DEV Community

Discussion on: JavaScript Interview Question #36: Can you add a new property to the JS array?

Collapse
 
aminnairi profile image
Amin

Yes you could. Even though this is considered a bad practice to extend global objects for demonstration purpose you could add a property to the Array prototype.

All future arrays will inherit this property after extension.

Array.prototype.greeting = "Hello world!";

const primes = [2, 3, 5, 7, 11];
const fruits = ["banana", "apple", "mango"];

console.log(primes.greeting); // "Hello world!"
console.log(fruits.greeting); // "Hello world!"

console.log(primes.length); // 5
console.log(fruits.length); // 3
Enter fullscreen mode Exit fullscreen mode