

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
- Related Questions & Answers
- How to get a number value of a string in Javascript?
- How to get the value of PI in JavaScript?
- How to get the value of the usemap attribute in JavaScript?
- How to get the last index of an occurrence of the specified value in a string in JavaScript?
- How to get the first index of an occurrence of the specified value in a string in JavaScript?
- How to get the length of a string in JavaScript?
- Get the name of a primitive type in Java
- How to get the absolute value of a number in JavaScript?
- Java Program to convert a Primitive Type Value to a String
- How to Get a slice of a primitive array in Java?
- How to get the value of the hreflang attribute of a link in JavaScript?
- How to get the value of the rel attribute of a link in JavaScript?
- How to get the value of the target attribute of a link in JavaScript?
- How to get the value of the type attribute of a link in JavaScript?
- How to get the value of the id attribute a link in JavaScript?