Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Basic javascript question about call() function: Conversion of non-string this values to strings

Reading MDN docs and have found this code:

const a = String.prototype.toUpperCase.call({
  toString: function toString() {
    return 'abcdef';
  }
});
// prints out 'ABCDEF'

Function call takes as first argument object with method toString, which means calling a function toUpperCase() on object or (correct me please if I’m wrong):

({ toString: function toString() { return 'abcdef'; }}).toUpperCase()

This code prints out ‘ABCDEF’, so how could toUpperCase() method invoke function toString() inside object that’s what I don’t understand.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’re calling toUpperCase passing it an object that isn’t a string but which has a toString method. Contrary to popular belief, toUpperCase doesn’t assume this will be a string. Instead, it converts whatever this is (in your case, the object with a toString method) to a string as one of its first steps (see the spec here¹). Doing that calls the toString method of your object (details here and here). At that point, toUpperCase has "abcdef" to work with, converts it to upper case, and returns it.

Conceptually (not exactly), toUpperCase does this:

function toUpperCase() {
    const S = String(this); // This is what triggers the call to `toString`
                            // on your object
    const L = /*...convert the characters in S to to upper case*/;
    return L;
}

¹ That’s for toLowerCase, but toUpperCase is defined by saying "This function behaves in exactly the same way as String.prototype.toLowerCase, except that the String is mapped using the toUppercase algorithm of the Unicode Default Case Conversion."

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading