3

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'}
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
snoob dogg
  • 2,491
  • 3
  • 31
  • 54

1 Answers1

4

Everything, even primitives, are essentially objects and can have members (properties, methods, etc). All the code in question is doing is attempting to find a member on 1 with the name foo which is not found so undefined is returned.

Igor
  • 60,821
  • 10
  • 100
  • 175