Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does JavaScript have a Map literal notation?

As of ES6, JavaScript has a proper Map object. I don't see a way to use a literal notation though, as you could with an Array or an Object. Am I missing it, or does it not exist?

Array: var arr = ["Foo", "Bar"];

Object: var obj = { foo: "Foo", bar: "Bar" };

Map: ???

like image 831
Matt Avatar asked Feb 26 '16 14:02

Matt


People also ask

Does JavaScript have a Map?

JavaScript 2015 (ES6) introduced a feature called Map. Not to be confused with the . map() array method, the built-in Map object is another way to structure your data. Maps are collections of distinct and ordered key-value pairs.

What is JavaScript literal notation?

The Object literal notation is basically an array of key:value pairs, with a colon separating the keys and values, and a comma after every key:value pair, except for the last, just like a regular array. Values created with anonymous functions are methods of your object. Simple values are properties.

Is a JavaScript Map a dictionary?

What is a Dictionary? A dictionary can also be called a map in JavaScript, and maps/dictionaries are used to store unique elements of key-value pairs. They are similar to the set data structure only that the set data structure stores a unique element of value value pairs.

What is the use of Map () in JavaScript?

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.


1 Answers

No, ES6 does not have a literal notation for Maps or Sets.

You will have to use their constructors, passing an iterable (typically an array literal):

var map = new Map([["foo", "Foo"], ["bar", "Bar"], …]);  var set = new Set(["Foo", "Bar", …]); 

There are some proposals to add new literal syntax to the language, but none made it into ES6 (and I'm personally not confident they will make it into any future version).

like image 193
Bergi Avatar answered Sep 22 '22 14:09

Bergi