Search code examples
javascriptbinaryundefinedbitwise-operators

How is undefined converted into binary in javascript?


How is undefined treated in Binary in javascript? It throws error when I do (undefined).toString(2).

But when I do

undefined & 0 //returns 0 
undefined & 1 //returns 0 
undefined | 0 //returns 0 
undefined | 1 //returns 1

One might guess that undefined might be converted into 0 . Or Is there any other thing going ?


Solution

  • Kind of. When bitwise operators (and other operators which only make sense in terms of math - such as - and * and ** etc) are used, both expressions are converted into numbers first.

    4. Let lnum be ? ToNumeric(lval).
    5. Let rnum be ? ToNumeric(rval).
    

    And ToNumeric does ToNumber which has

    Argument Type   Result
    Undefined       Return NaN.
    

    And then the binary operators call ToInt32 on each operator, which has

    1. If number is NaN, +0𝔽, -0𝔽, +∞𝔽, or -∞𝔽, return +0𝔽.

    So they're effectively converted into NaN in preparation for the mathematical operation, and then NaN gets converted to 0 for the binary operation.

    (undefined).toString(2) doesn't work because accessing a property (like toString) of an expression only works if the expression is an object, or a primitive that can be wrapped in an object. Undefined and null are not objects, nor can they be converted into one, so trying to access any property of them throws.