I know that JavaScript support Autoboxing (the automatic conversion from a primitive data type to its object counterpart), but does JavaScript also support Unboxing (the automatic conversion from an object to its primitive data type counterpart)?
Asked
Active
Viewed 261 times
1
-
2"Autoboxing" is not really the correct term. Not in the sense of Java, at least where autoboxing can have serious implication for speed. Similarly "unboxing" isn't quite correct, either. There is *type coercion* but I wouldn't want to mix it with boxing/unboxing. – VLAZ Sep 14 '21 at 18:27
2 Answers
0
but does JavaScript also support Unboxing (the automatic conversion from an object to its primitive data type counterpart)
Yes it does. This is quite what happens for example when you do:
'' + { };
Which gets you:
'[object Object]'
Although this doesn't exactly fit "Unboxing".
I think a better example would be to use either a String
or a Number
. Since those are the values that actually get boxed.
new String('test') + '!!!' // "test!!!"
2 ** (new Number(2)) // 4
2 + (new Number(2)) //4
2 / (new Number(2)) //1

MinusFour
- 13,913
- 3
- 30
- 39
-
2`'' + new Number(42)` will not actually unbox the object. It converts it to a string which is a different mechanism. – VLAZ Sep 14 '21 at 18:28
-
But it does if you do `5 + new Number(42)`. Context is important here. – MinusFour Sep 14 '21 at 18:32
-
1Type coercion is still a different mechanism to boxing/unboxing in the Java sense. – VLAZ Sep 14 '21 at 18:33
-
Well, there's at least a definition given by the oracle docs that fits this [behavior](https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html). – MinusFour Sep 14 '21 at 18:38
-
-
The compiler converts the type of the value in JavaScript? I didn't know we either had a compiler in JavaScript or that the types changed on stuff like assignment and method calls. (well compiler is an implementation detail, of course. It doesn't really work like the Java compiler) – VLAZ Sep 14 '21 at 18:40
-
That would be an implementation detail for sure... I believe the standard does allow for implementations to even circumvent the intermediary objects. – MinusFour Sep 14 '21 at 18:45
0
The easiest way to obtain the underlying primitive value from an object wrapper is to use the valueOf() method:
const a = Object(false);
a == false; //true
a === false //false
a.valueOf() == false //true
a.valueOf() === false //true

Vojin Purić
- 2,140
- 7
- 9
- 22