Metamorphing Machine I rather be this walking metamorphosis
than having that old formed opinion about everything!

Four "different" uses of Javascript operators

I program in VB, VBScript, VB.NET, and C#. I played with assembly, C, TypeScript, and even J#.
And Javascript. There are four uses of Javascript operators that I find intriguing. Let's see what they are.

Note: If you know Wasm, then nothing I'll be talking about is new to you.
  1. In most programming languages, the unary "+" operator (identity) is useless. It does nothing, returning its operand untouched. Not so in Javascript. It can be used to convert a string into a number (or NaN if the string is not convertible, like "pineapple", for instance.)
    +"3.14159" yields 3.14159.

  2. When one wants to convert a double to an integer, one uses Math's methods, like floor, ceil, or round. But there's another way: One can OR the number with zero, like let n = 3.14159 | 0;
    It has the same effect as rounding it to zero decimal places.

  3. Javascript has falsy values (0, 0n, null, undefined, false, NaN, and ""), and truthy ones (everything else.)
    One way to convert any value into true or false is to use a double not (!!).
    The first ! converts any truthy values to false, and any falsy values to true. The second one fixes it, so truthy values become true and falsy values, false.

  4. The most baffling operator use I've ever seen in Javascript is right-unsigned-shifting by zero.
    Javascript numbers are doubles, so they are always signed, or "there isn't such a thing as unsigned numbers in Javascript." Right-shifting them with >> preserves their signs.
    To right-shift not preserving the sign, Javascript has the >>> operator. So, what do you think is the outcome of such an odd expression:

    let n = -1;
    n >>>= 0;

    It seems nothing would change, but it reinterprets n as an unsigned 32-bit integer, so, in our example, -1 becomes 4294967295.
Next week I'll mourn a (second) death of a hero.
May 2022 be a whole lot better than 2021 to us all!

Andrej Biasic