Today I came accross a strange thing in Javascript. When in Chrome console if I execute :
> 1["foo"]
Chrome console returns :
undefined
I was expecting an error though. How is it possible? I fall on that by studying the underscore.js (an old version) invoke
method that seems to use that JavaScript property:
// Invoke a method (with arguments) on every item in a collection.
_.invoke = function(obj, method) {
var args = slice.call(arguments, 2);
var isFunc = _.isFunction(method);
return _.map(obj, function(value) {
var func = isFunc ? method : value[method];
return func == null ? func : func.apply(value, args);
});
};
As you can see, value
could be a number and if 1["foo"]
was raising an error, that code would be unsafe as I could do the following by mistake:
var a = {'foo' : 1}
_.invoke(a, 'foo'}