How and why does ‘a'[‘toUpperCase’]() in JavaScript work?

How and why does ‘a'[‘toUpperCase’]() in JavaScript work?

JavaScript keeps surprising me and this is another instance. I just came across some code which I did not understood at first. So I debugged it and came to this finding:
alert(‘a'[‘toUpperCase’]()); //alerts ‘A’

Now this must be obvious if toUpperCase() is defined as a member of string type, but it did not make sense to me initially.
Anyway,

does this work because toUpperCase is a member of ‘a’? Or there is something else going on behind the scenes?
the code I was reading has a function as follows:
function callMethod(method) {
return function (obj) {
return obj[method](); //**how can I be sure method will always be a member of obj**
}
}

var caps2 = map([‘a’, ‘b’, ‘c’], callMethod(‘toUpperCase’)); // [‘A’,’B’,’C’]
// ignoring details of map() function which essentially calls methods on every
// element of the array and forms another array of result and returns it

It is kinda generic function to call ANY methods on ANY object. But does that mean the specified method will already be an implicit member of the specified object?

I am sure that I am missing some serious understanding of basic concept of JavaScript functions. Please help me to understand this.

Related:  Why does IE nuke window.ABC variables?

Solutions/Answers:

Solution 1:

To break it down.

  • .toUpperCase() is a method of String.prototype
  • 'a' is a primitive value, but gets converted into its Object representation
  • We have two possible notations to access object properties/methods, dot and bracket notation

So

'a'['toUpperCase'];

is the access via bracket notation on the property toUpperCase, from String.prototype. Since this property references a method, we can invoke it by attaching ()

'a'['toUpperCase']();

Solution 2:

foo.bar and foo['bar'] are equal so the code you posted is the same as

alert('a'.toUpperCase())

When using foo[bar] (note tha lack of quotes) you do not use the literal name bar but whatever value the variable bar contains. So using the foo[] notation instead of foo. allows you to use a dynamic property name.


Let’s have a look at callMethod:

First of all, it returns a function that takes obj as its argument. When that function is executed it will call method on that object. So the given method just needs to exist either on obj itself or somewhere on its prototype chain.

In case of toUpperCase that method comes from String.prototype.toUpperCase – it would be rather stupid to have a separate copy of the method for every single string that exists.

Related:  Check if option is selected with jQuery, if not select a default

Solution 3:

You can either access the members of any object with .propertyName notation or ["propertyName"] notation. That is the feature of JavaScript language. To be sure that member is in the object, simply check, if it is defined:

function callMethod(method) {
    return function (obj) {
        if (typeof(obj[method]) == 'function') //in that case, check if it is a function
           return obj[method](); //and then invoke it
    }
}

Solution 4:

Basically javascript treats everything as an Object, or rather every object can be viewed as a dictionary/associative-array. And functions/methods are defined the exact same way for the object – as an entry in this associative array.

So essentially, you’re referencing/calling (notice the ‘()‘ ) the ‘toUpperCase’ property, of the ‘a’ object (which is a string type, in this case).

Here’s some code of the top of my head:

function myObject(){
    this.msg = "hey there! ;-)";
    this.woop = function(){
        alert(this.msg); //do whatever with member data
    }
}

var obj = new myObject();
alert( obj.msg );
alert( obj['msg'] );
obj['woop']();

Solution 5:

anyObject['anyPropertyName'] is the same as anyObject.anyPropertyName when anyPropertyName hasn’t problematic characters.

Related:  Highcharts - how to have a chart with dynamic height?

See Working with Objects, from the MDN.

The toUpperCase method is attached to the type String. When you call a function on a primitive value, here 'a', it is automatically promoted to an object, here a String :

In contexts where a method is to be invoked on a primitive string or a
property lookup occurs, JavaScript will automatically wrap the string
primitive and call the method or perform the property lookup.

You can see the function exists by logging String.prototype.toUpperCase.

Solution 6:

So in Javascript, objects are objects. That is they’re of this nature {}. Object properties can be set using either of these: a.greeting = 'hello'; or a['greeting'] = 'hello';. Both ways work.

Retrieval works the same. a.greeting (without quotes) is 'hello', a['greeting'] is 'hello'. Exception: if the property is a number, only the bracket method works. The dot method doesn’t.

So 'a' is an object with 'toUpperCase' property which is actually a function. You can retrieve the function and call it subsequently either way: 'a'.toUpperCase() or 'a'['toUpperCase']().

But imo the better way to write the map function would be as

var caps = ['a','b','c'].map( function(char) { return char.toUpperCase(); } )

Who needs the callMethod function then?