What are exponential notation and NaN in JavaScript?
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.
Exponential notation
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:
Code example
console.log(8e11);console.log(8E11);console.log(34e-4);console.log(4.5E-6);
Explanation
Lines 1–2: The example
8e11returnsmultiplied by to the power of , and 8E11also produces the same result.Lines 3–4: These examples show the usage of values using a negative index as a power.
34e-4returnsmultiplied by to the power of . 4.5E-6returnsmultiplied by to the power of .
NaN
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
Code example
console.log('hello' * 9);console.log(0/0);console.log(Math.sqrt(-16));console.log(parseInt("Hello"));
Note:
parseIntis used to convert number string ("123") into a numeric value.
Explanation
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
parseInta string into a numeric value, which results inNaN.
Free Resources