The next features of ES2020 or ES11 that you will learn are: new bigint
data type and Nullish Coalescing (??
) operator.
Big Int, very large integers
The new bigint
data primitive allows you to handle very large integers. There are two ways to create a bigint
: the integer followed by n
or by the BigInt
function
const number1 = 45nconst number2 = BigInt(45)typeof 45n .
JavaScript has numeric limits, a maximum Number.MAX_SAFE_INTEGER
and a minimum Number.MIN_SAFE_INTEGER
.
const max = Number.MAX_SAFE_INTEGERconst min = Number.MIN_SAFE_INTEGERconsole.log(max) console.log(min)
After the limits, the calculations show erroneous results. The bigint
helps to handle integer operations outside the mentioned limits.
const increment = 2const number = Number.MAX_SAFE_INTEGER + incrementconst bigInt = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(increment)console.log(number) console.log(bigInt)
The same amount is added to both data types, however, the numeric type gives a different result than expected.
Nullish Coalescing Operator
The nullish coalescing (??
) operator consists of evaluating a variable if it is undefined
or null
to assign it a value.
The following example reads as: is user.name
undefined
or null
? If so, assign it a default value "Andres",
otherwise assign the value of user.name.
const user1 = {}const name1 = user1.name ?? "Andres"const user2 = {name: "Juan"}const name2 = user2.name ?? "Andres"console.log(name1) console.log(name2)
Difference between the OR operator and the Nullish coalescing operator
The OR operator(||
) evaluates a falsy value. A falsy value is one that is false in a boolean context, these are: 0
, ""
(empty string), false
, NaN
, undefined
or null
.
You may receive a variable with a falsy value that you need to assign to another variable, other than null
or undefined
. If you evaluate with the OR operator, it will change it, causing an erroneous result.
const id = 0const orId = id || "No id"const nullishId = id ?? "No id"console.log( orId ) ' console.log( nullishId )
Contribution created by Andrés Guano (Platzi Contributor).
Want to see more contributions, questions and answers from the community?