Understanding exponential notation and NaN (Not a Number) in JavaScript is key for handling numerical data effectively. Exponential notation simplifies the representation of large or small numbers, making code more readable. Knowing how to work with NaN helps us gracefully handle errors and unexpected values. Let’s discuss them one by one.
In JavaScript, we can represent numbers in the form of exponential notation. It is used when we want to represent a large number or a very small number in scientific notation, which is basically multiplied by 6.022e23
is a number, which, in scientific notation, is e
we can also use capital E
. Both produce the same result.
Let’s see some more examples of using exponential notation:
console.log(8e11);console.log(8E11);console.log(34e-4);console.log(4.5E-6);
Lines 1–2: The example 8e11
returns 8E11
also produces the same result.
Lines 3–4: These examples show the usage of values using a negative index as a power.
34e-4
returns
4.5E-6
returns
NaN
is a specific error code that stands for Not a Number. It is used when an operation is tried, and the outcome is not numerical, such as when attempting to multiply a string by a number. NaN
is often the result of invalid mathematical operations, such as dividing
console.log('hello' * 9);console.log(0/0);console.log(Math.sqrt(-16));console.log(parseInt("Hello"));
Note:
parseInt
is used to convert number string ("123"
) into a numeric value.
Line 1: It tries to multiply a string with a number, so it returns a NaN
.
Line 2: It uses an invalid mathematical division, which also results in NaN
.
Line 3: It tries to calculate the square root of a negative number, which results in NaN
.
Line 4: It tries to parseInt
a string into a numeric value, which results in NaN
.
Free Resources