How to get the primitive value of string in Javascript?


In JavaScript there are 5 primitive types: undefined, null, boolean, string and number. Everything else is an object.

The primitive types boolean, string and number can be wrapped by their wrapper object, i.e., instances of the Boolean, String and Number constructors respectively.

To get the back the primitive values back from the object wrappers, we need to call the valueOf method on the objects.

Example

console.log(typeof true);
console.log(typeof new Boolean(true));
console.log(typeof (new Boolean(true)).valueOf());
console.log(typeof "abc");
console.log(typeof new String("abc"));
console.log(typeof (new String("abc")).valueOf());
console.log(typeof 123);
console.log(typeof new Number(123));
console.log(typeof (new Number(123)).valueOf());

Output

"boolean"
"object"
"boolean"
"string"
"object"
"string"
"number"
"object"
"number"

As you can swee here the types of the primitives is boolean, string or number while their wrappers is object. As soon as we get values using valueOf, we again get primitives back.

But, the primitives also have properties in JS. This is because JavaScript coerces between primitives and objects based on need. So if we access the length property on this primitive, it is wrapped in a object, this property is accessed and primitive is unwrapped again.

raja
Published on 19-Sep-2019 08:09:16
Advertisements