Check out my books on Amazon at https://www.amazon.com/John-Au-Yeung/e/B08FT5NT62
Subscribe to my email list now at http://jauyeung.net/subscribe/
JavaScript is partly an object-oriented language.
To learn JavaScript, we got to learn the object-oriented parts of JavaScript.
In this article, we’ll look at primitive wrappers.
Boolean
The Boolean
can be used as a factory function or a constructor.
For instance, we can write:
const b = new Boolean();
and we get a boolean wrapper object returned.
We can convert it back to a primitive value with valueOf
:
b.valueOf();
A better use of the Boolean
function is to use it as a factory function.
For example, we can write:
Boolean("foo");
then we get true
.
It’ll return true
for anything truthy and false
otherwise.
Boolean
without new
returns a primitive value.
Number
Number
can also be used as a constructor or a factory function.
For instance, if we have:
const n = Number('12');
then we return the number 12.
And if we have:
const n = new Number('12');
then we return an object with value 12.
So we should use it without new
to eliminate confusion.
Number
also has some static properties.
Number.MAX_VALUE
is 1.7976931348623157e+308
.
There’s also the Number.POSITIVE_INFINITY
which is Infinity
.
And Number.NEGATIVE_INFINITY
which is -Infinity
.
The toFixed
method formats a number to a decimal number with the given number of fractional digits.
For instance, we can write:
(123.456).toFixed(1);
We have “123.5”
.
The toExponential
method returns the number string in exponential notation.
For instance, if we have (12345).toExponential()
, then we get:
"1.2345e+4"
The toString
method lets us convert numbers to number strings of various bases.
For instance, we can write:
(255).toString(2)
Then we convert the number to the binary string:
"11111111"
And we can write:
(255).toString(16)
and get:
"ff"
To convert it to a decimal, we write:
(255).toString(10)
And we get:
"255"
String
The String
function is used to create a string.
We can use it as a constructor or factory function.
We don’t want to create an object with it to reduce confusion, so we should use it as a factory function.
For instance, we can write:
const obj = new String('foo');
then we create a string wrapper object.
To convert it to a primitive value, we call valueOf
:
const s = obj.valueOf();
It’s better just to create a string as a string literal:
const s = 'foo';
We can also use the function to convert non-strings to strings:
const s = String(123);
We can get the number of characters in a string with the length
property.
So if we have:
const s = 'foo';
Then s.length
is 3.
If we pass in an object to String
, then the toString
method will be called.
So:
String({
a: 1
});
returns:
"[object Object]"
And:
String([1, 2, 3]);
returns:
"1,2,3"
Conclusion
Boolean
, Number
, and String
functions let us create primitive values.
We should use them as factory functions to convert between different primitive types.