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 ?
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
- 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With