News for hackers. Stuff that matters.
Re:The complete guide to working with strings in modern Java... by eyelidlessness on Wednesday April 14, 2021 @08:39PM (#26814904)
It’s useful to know about even if you have no use case for it. Because this conversion happens every time you access a property on any JS primitive. For example, this:

    str.toUpperCase()
Is actually doing this:

    new String(str).toUpperCase()
...hand waving away obvious optimizations that surely occur for multiple property access.

There may be cases, for instance a series of imperative synchronous hot loops, where this has a meaningful performance impact.

Another thing that’s important to know is that you can do this:

    Object.assign(str, {
        anythingAt: ‘all’
    })
And you’ve now mutated your string into a String. This breaks a buuuuunch of expected behaviors with primitives, such as === and the default Array#sort comparator.

Edit: this last one bit me experimenting with a runtime implementation of a common pattern in TypeScript to define nominal types for primitives (e.g. to distinguish a known valid URL from a regular string) called branding[1]. The approach is useful if you’re obsessive about type safety, but flawed because it almost certainly misrepresents the runtime type. I tried to use Object.assign to get that much more type safety and... I got the opposite! I got a String claiming to be a string, which broke all sorts of stuff, including the aforementioned === and Array#sort.

1: https://medium.com/@KevinBGreene/surviving-the-typescript-ec...

There are no comments on this comment yet.