Search code examples
javascripttypestype-conversionanonymous-function

JS: Do anonymous functions automatically do data type conversion (casting) on parameters to match use in the function?


I'm writing a function to sort an object based on its keys, based on the example here: github

The relevant lines:

const unsortedObjArr = [...Object.entries(myObj)]
const sortedObjArr = unsortedObjArr.sort(
  ([key1, value1], [key2, value2]) => key1.localeCompare(key2)
)

In testing to make it more robust, I found (as expected) that these throw errors:

(10).localeCompare(11);
const ten = 10;
ten.localeCompare(11);

However, I've tested the sort function on an object with keys of type number and boolean, and it performs exactly the same as 2 other functions which use these sort functions instead:

([key1, value1], [key2, value2]) => key1.toLocaleString().localeCompare(key2)
([key1, value1], [key2, value2]) => key1.toLocaleString().localeCompare(key2.toLocaleString())

(I've noticed that localeCompare does type conversion and the second version is unnecessary -- on its own (outside a function), key1.toLocaleString().localeCompare(key2) will work without error regardless of the types of key1 and key2 -- thus my question just pertains to the data type conversion of key1.)

Do anonymous functions in JavaScript do automatic type conversion of their parameters to match their use in the function? If not, why does the sort function work with key1.localeCompare(key2), even on objects with non-string keys?


Solution

  • I've tested the sort function on an object with keys of type number and boolean

    You can't have such objects.

    Property names can only be strings and Symbols.

    Your numbers and booleans were cast to strings, but they were cast when you attempted to create the property on the object, not when the values were passed to the arrow function.