bhuwan
bhuwan

Reputation: 107

How i am able to add a key in a Array in Javascript? What is happening behind the scene

Let say I have an Array a = [1,2,3,4,5]. And I am adding a key in the Array and now a is working as an Array and Object both.

const a = [1, 2, 3, 4, 5];
a['key'] = 'hello';
console.log(a); // [1, 2, 3, 4, 5, key: "hello"]

Upvotes: 0

Views: 43

Answers (1)

AnishJoshi
AnishJoshi

Reputation: 84

Arrays are list-like objects whose prototype has methods to perform traversal and mutation operations. Neither the length of a JavaScript array nor the types of its elements are fixed. Setting using the key in the Array using bracket notation will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

Upvotes: 3

Related Questions