To create a map in ES6, should you say Map()
or new Map()
?
Both seem to work fine in node --harmony
.
The draft spec says "The Map constructor is the %Map% intrinsic object and the initial value of the Map property of the global object. When Map is called as a function rather than as a constructor, it initializes its this value with the internal state necessary to support the Map.prototype built-in methods." which also seems to suggest they should both work.
Given that, Map()
would seem better because shorter, though that's a subjective judgment; objectively they seem interchangeable?
Although current browsers appear to permit the use of Map()
without new
(as shown in @RobG's answer), this is in fact incorrect.
Because of a stability issue, Node.js v0.10 uses an older version of V8 (the JavaScript engine in Node.js) which does not throw if you do Map()
.
Node.js v0.10 uses V8 v3.14.5, but the issue with Map()
not throwing was only fixed in v3.20.12.
Chrome, which uses a newer version of V8, throws an error if you don't use new
. I'm not sure why Firefox doesn't throw an error though.
According to the current draft specification, it should be impossible to call Map()
without new
:
- Let map be the this value.
- If Type(map) is not Object then, throw a TypeError exception.
- If map does not have a [[MapData]] internal slot, then throw a TypeError exception.
- If map’s [[MapData]] internal slot is not undefined, then throw a TypeError exception.
Usually in a constructor the object that is supposed to be created is this
. It requires that the object passed is an instance of Map
, and that it has not been initialised yet ([[MapData]]
must be undefined).
Apparently this is because it hinders the subclassing of native constructors, which will be possible in ES6.