Is it guaranteed that map.get(Constants.COUNTRY) will always return something?
For map.get(Constants.COUNTRY)
to always return your original value, a couple things have to be true.
You have to make sure that Constants.COUNTRY
can never be assigned a different value either because the .COUNTRY
property was reassigned or because the Constants
object was replaced with something else that had a different .COUNTRY
property value.
You have to make sure that nobody can ever remove that key from the map
object.
If you can assure these two things, then yes map.get(Constants.COUNTRY)
will always return your desired value. But, if either of those are not necessarily true, then you are not assured of always getting your value from the map.
You can assure that Constants.COUNTRY
cannot be changed by freezing the Constants
object or by setting that property to be configurable to it cannot be removed or written to. To assure that the Constants
object cannot be replaced, it would be best for it to be const
as in your second code block.
I don't know of a way to assure that nobody can call map.delete(Constants.COUNTRY)
except by keeping the map
object private so foreign code cannot get to it.
If you had any reason to want to prevent enumeration of the keys in the map (to make it harder for someone to discover a key perhaps), then you could use a WeakMap
instead of a Map
.
Is the performance as good as using strings as key?
You'd have to test a specific Javascript implementation to be sure about performance. There is no required implementation reason that one or the other should be faster - it will just depend upon the internals of the implementation.
I created a jsPerf test case to compare string lookups to object lookups. Feedback is welcome on improving how this is tested/measured, but using the current scheme where I create 10,000 string keys and 10,000 object keys in a map and then compare accessing 1000 of each, I find varying results.
Chrome is ~20% slower to access the object keys.
Firefox is ~20% slower to access the string keys.
Edge is ~27% slower to access the string keys.
Is it also more appropriate to declare it as a variable instead of a class?
As discussed, your second const
form has the advantage that Constants
cannot be reassigned.