HRS - Ask. Learn. Share Knowledge. Logo

In Computers and Technology / High School | 2025-07-08

What is the output of the below given JavaScript code snippet? var a = new Array(); a["name"] = "Rihana"; a["place"] = "Hyderabad"; (a) Options: 1. [name: 'Rihana', place: 'Hyderabad'] 2. ["Rihana", "Hyderabad"] 3. Array does not support string indexing 4. {name:["Aravind"], place:["Chidambaram"]}

Asked by rubyheartscats2572

Answer (1)

In JavaScript, when you use an array and assign values using string keys, it behaves more like an object rather than a traditional array where elements are accessed with numerical indices.
Here's the step-by-step explanation:

Array Declaration: var a = new Array(); creates an empty array.

String Indexing:
- a["name"] = "Rihana"; assigns "Rihana" to the key "name". - a["place"] = "Hyderabad"; assigns "Hyderabad" to the key "place".

Array vs Object: Even though a is declared as an array, using string keys converts it to an associative array, which is equivalent to an object in JavaScript.

Output: Using string keys doesn't store values in the array part of a. Instead, it adds properties to a like an object.


Therefore, using console.log(a) would display an empty array [], as numerical indices have not been used. However, accessing a.name or a["name"] gives "Rihana", and a.place or a["place"] gives "Hyderabad".
Considering the options given:

[name: 'Rihana', place: 'Hyderabad'] - This format suggests object notation, but arrays with string indices act like objects without displaying this format.

["Rihana", "Hyderabad"] - This suggests a typical array display, which isn't applicable here because we aren't using numeric indices.

Array does not support string indexing - Closest to reality since arrays are not designed for string indexing, but allow it by behaving like objects.

{name:["Aravind"], place:["Chidambaram"]} - Is unrelated to the operations in the code.


Right Choice: Option 3. Array does not support string indexing. While arrays can technically handle such operations by treating them as objects, they are not indexed in the typical array manner.

Answered by MasonWilliamTurner | 2025-07-21