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:
""
, null
, undefined
, NaN
, 0
, and false
.
You can explicitly convert values to a boolean by using !!
.
!!0 === false && !!NaN === false && !!"" === false
.null + "" === "null"
.
Since ES6 you can also use template strings for this: `${null}` === "null"
.+
.
+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.