JavaScript has 6 primitive data types.
They are string, number, boolean, null, undefined, and symbol.
What's a symbol you ask? ECMAScript 2015 introduced them. They are a way to create globally unique values/identifiers with descriptions. This article does a great job explaining them.
And then there are objects. We will talk about them in another article.
Here are 3 quick tips for converting data to one specific primitive:
-
Boolean conversion. All JS values are truthy, except
""
,null
,undefined
,NaN
,0
, andfalse
. You can explicitly convert values to a boolean by using!!
.!!0 === false && !!NaN === false && !!"" === false
. -
String conversion. Convert any primitive value to a string by adding an empty string.
null + "" === "null"
. Since ES6 you can also use template strings for this:`${null}` === "null"
. -
Number conversion. The primitive values string, null, and boolean can be converted to numbers with
+
.+null === 0 && +true === 1 && +false === 0 && +'0' === 0 && +'100' === 100
.
You can also use the global methods String()
, Number()
, and Boolean()
.
They make your conversion explicit and readable.
Top comments (0)