Why JavaScript does not support arrays with named indexes? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why JavaScript does not support arrays with named indexes?

I didn’t understand on the lesson!

20th Apr 2019, 7:15 PM
Rudro Saha🇧🇩
Rudro Saha🇧🇩 - avatar
3 Answers
+ 5
JavaScript allows for named indexes (known as "keys"), they're known as JavaScript Objects. You can create an object like this: let fruitPrices = { "apples": 3, "oranges": 2, "watermelons": 4 } You can access members of an object using the dot operator or the array-access operator. Ex: let applePrice = fruitPrices.apples let watermelonPrice = fruitPrices["watermelons"] console.log(applePrice) console.log(watermelonPrice) /* outputs: >3 >4 */ The dot operator method is useful for writing quick code, but using the array-access operator is more versatile, since it allows you to use variables to access elements. For example: let str = "oranges" console.log(fruitPrices[str]) //output: 2 let str = "oranges" console.log(fruitPrices.str) //output: null In the second example, the code thinks that we are trying to access a member of the fruitPrices object with the key "str". However, with the first method, we make it clear that we want to access the member with the key stored inside the str variable, "oranges".
20th Apr 2019, 8:17 PM
Jack McCarthy
Jack McCarthy - avatar
+ 5
In addition to the excellent answer posted by Jack McCarthy, the Javascript Map object is a great alternative to consider. Check out the link below to better understand the differences between using objects vs Maps. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map#Objects_and_maps_compared
22nd Apr 2019, 3:58 AM
David Carroll
David Carroll - avatar
+ 1
Thanks
21st Apr 2019, 2:22 AM
Rudro Saha🇧🇩
Rudro Saha🇧🇩 - avatar