Andrew Lichtenberg
Andrew Lichtenberg

Reputation: 123

Javascript map returning function

I have an interesting problem with a map that is broken in Firefox. When I test if an empty map has the string "watch" it will return true and return the function watch(). I want that to return false since I haven't added the key "watch" to the map. A quick example

I normally create a basic map like

var myMap = {}
myMap["apple"] = 1;
myMap["pear"] = 2;

And to test if the map has the object I would write

if ("apple" in myMap) { ... }

And the problem is when I want to add the string "watch" to the map if the map doesn't all ready contain it. So when I check to see if the map contains "watch" it returns true.

if ("watch" in myMap) { ... }
// This also returns true.  and returns the function watch()

Any ideas on how to avoid this behaviour?

Thanks

Upvotes: 1

Views: 85

Answers (2)

Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10857

You can try

var myMap = {};
myMap["apple"] = 1;
myMap["pear"]=2;

if (myMap.hasOwnProperty("apple")) {

}

if (myMap.hasOwnProperty("watch")) {

}

Upvotes: 2

elclanrs
elclanrs

Reputation: 94101

It's because an object literal inherits from the Object prototype. You can create an empty object, that inherits from nothing:

var myMap = Object.create(null);

Or check with hasOwnProperty:

if (myMap.hasOwnProperty('watch')) {
  ...
}

Upvotes: 2

Related Questions