DEV Community

loading...
Cover image for JavaScript Interview Question #36: Can you add a new property to the JS array?

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

Coderslang: Become a Software Engineer
Teaching you to code at js.coderslang.com - JavaScript, HTML, CSS, Node.js, React.js, React Native
Originally published at learn.coderslang.com on ・1 min read

js-test-36

Does the new array property affect its length? Is such an assignment valid at all?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

JavaScript arrays are used to store values in an orderly fashion. Normally, to add a new element, you should use the built-in push() function.

But, in JS, all arrays are objects in the first place. Which means you can add new fields to them.

The assignment arr.greeting = 'Hello, world!' won’t raise any errors and is perfectly fine from the language standpoint.

Once it’s executed, the array will have an extra property greeting.

The length of an array won’t change as Hello, world! isn’t considered one of the elements of the array.


ANSWER: the length of an array won’t change and will remain equal to 4. The second console.log prints out Hello, world! to the screen.

Learn Full-Stack JavaScript

Discussion (3)

Collapse
zer0 profile image
zer0

Quick question:
Wouldn’t you be able to extend the prototype too to produce the same behaviour ?

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
Collapse
coderslang profile image
Coderslang: Become a Software Engineer Author

Yes, you can. JS is wild. You can do pretty much anything you can think of.

@aminnairi shows a great example

Forem Open with the Forem app