One can use typeof to determine whether a value is primitive or boxed.
Consider:
typeof "foo"; // "string"
typeof new String("foo"); // "object"
In combination with Object.prototype.toString we could define the following two functions
var toString = Object.prototype.toString;
var is_primitive_string = function(s) {
return toString.call(s) === "[object String]" && typeof s === "string";
};
var is_boxed_string = function(s) {
return toString.call(s) === "[object String]" && typeof s === "object";
};
Are there any use cases for these two functions? (Or similar functions for Number, Boolean, etc).
The concept behind this question came from the following Comment by T.J.Crowder.
Should we ever care whether a value we have is primitive or boxed?
I’d say there’s virtually no point, you almost never care whether you’re dealing with a
stringprimitive or aStringobject.There are edge cases. For instance, a
Stringobject is an actual object, you can add properties to it. This lets you do things like this:If calling code passes in a
stringprimitive:…
arggets promoted to aStringobject and gets a property added to it, but thatStringobject isn’t used by anything aftertestreturns.In contrast, if calling code passes in a
Stringobject:…then the property is added to that object and the calling code can see it. Consider (live copy):
Output:
Note that
s2.foois a string, buts1.fooisn’t (becauses1was a string primitive, the object created when we promoted it intesthas nothing to do with the calling code).Is there any use case for this? Dunno. I’d say it would be an extremely edgy edge case if so.