23
loading...
This website collects cookies to deliver better user experience
string
number
Boolean
undefined
null
Symbol
BigInt
typeof
operator to return a variable type, we return the variable’s value type.string
, number
, and Boolean
primitive types. There's no way in JavaScript to coerce a value type to object
or function
.String()
, Number()
, and Boolean()
.Number()
function coerces the value type that passes to the function, then to a number. When a type can't be coerced to a number, the returned result is NaN
.Number()
function:Number("42"); // 42
Number(""); // 0
Number(true); // 1
Number(false); // 0
Number(null); // 0
Number(undefined); // NaN
null
to a number returns 0
while converting undefined
to a number returns NaN
. Both operations should return NaN
since both value types are clearly not valid numbers.0
. This is another weird part of JavaScript because this value type is clearly not a valid number yet it still converts to 0
.Number()
function may seem unexpected, the ECMAScript specification clear states these discrepancies. But without reading the ECMA specification, developers may not realize this is just how JavaScript is written.null
and undefined
. The ECMAScript specification Number()
function with a null value type it returns 0
, and whenever we use the same function with undefined
it returns NaN
.ToNumber
is a type conversion name that the ECMAScript specification uses when referring to an operation where a value converts to a number. Number()
is a primitive wrapper object in JavaScript that converts a value to a number. This is the same with ToBoolean
, which we will cover later.ToNumber
operation converts them to:Number()
function with an empty string and received a 0
. This is something that is explicit in the ECMAScript specification as well:A StringNumericLiteral
that is empty or contains only white space is converted to +0. – ECMAScript 2015 Language Specification
String()
function. To implicitly coerce a value to a string, we can use the +
operator with any operand that is a string.String("42"); // "42"
String(true); // "true"
String(false); // "false"
String(null); // "null"
String(undefined); // "undefined"
10 + "10" // "1010"
20 + "200" // "20200"
0.212 + "1" // "0.2121"
Boolean()
function. To implicitly coerce a value to Boolean, we can use logical operators, such as ||
, &&
, and !
in a logical context.Boolean() function
is very clean and helpful. We can clearly see which results we receive depending on the value type that we pass:Boolean('') // false
Boolean(0) // false
Boolean(-0) // false
Boolean(NaN) // false
Boolean(null) // false
Boolean(undefined) // false
Boolean(false) // false
true && false // false
true && true // true
true || false // true
true || !false // true
"name" || 0 // "name"
"name" || [] // "name"
"" || [1, 2, 3] // [1, 2, 3]