This page looks best with JavaScript enabled

Associative arrays in Javascript

 ·   ·  ☕ 1 min read

tldr; There are no associative arrays in Javascript. But there is indeed a credible alternative.

In PHP, we can do the following -

1
2
3
4
var fruits={};
fruits[3]="apple";
fruits[2]="orange";
fruits[1]="pear";

Javascript does not have associative arrays.

All you can do is -

1
const fruits = ["apple", "orange", "pear"];

Yes, you can define props for the array itself, but that is an altogether different thing.

1
fruits["grape"] = "white";

The above statement does not “modify the array elements”. It just adds a prop to the array object. So, you cannot iterate and the length of array stays the same as before.

The alternative for associative arrays is just an object.

1
2
3
const fruits = { 3: "apple", 2: "orange", 1: "pear" };
console.log("fruits: ", fruits);
// fruits:  { '1': 'pear', '2': 'orange', '3': 'apple' }

You do not have access to all the array methods, but could apply powerful iterations for objects through methods like Object.values.forEach().

You can observe the similarities between the PHP and Javascript way of doing things in the below code-

1
2
echo json_encode(new Array(3=>"apple", 2=>"orange", 1=>"pear"));
// {"3":"apple","2":"orange" , "1":"pear"}
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things