js create disctionary in javascript

In JavaScript, we can create a dictionary using an object literal or by using the Object constructor method. Here's an example using object literal:

index.tsx
// create an empty dictionary object
let dict = {};

// add key-value pairs to the dictionary
dict['apple'] = 1;
dict['banana'] = 2;
dict['orange'] = 3;

// print the dictionary object
console.log(dict); // {apple: 1, banana: 2, orange: 3}
240 chars
11 lines

Alternatively, we can use the Object constructor method to create a dictionary as follows:

index.tsx
let dict = new Object();

// add key-value pairs to the dictionary
dict['apple'] = 1;
dict['banana'] = 2;
dict['orange'] = 3;

// print the dictionary object
console.log(dict); // {apple: 1, banana: 2, orange: 3}
213 chars
10 lines

In both cases, we first create an empty object, and then add key-value pairs to the dictionary by specifying the key and its associated value using square brackets. We can then access the values in the dictionary using their respective keys.

gistlibby LogSnag