Monday, 28 October 2024

Special numbers in Javascript

In JavaScript, there are several special numerical values that behave differently from typical numbers. These include:

 

1.   Infinity

2.   -Infinity

3.   NaN (Not-a-Number)

 

Infinity

Infinity represents a value that is greater than any finite number. It is the result of operations like dividing a positive number by 0.

 

infinity.js 

let positiveInfinity = 1 / 0;
console.log(positiveInfinity); // Output: Infinity

 

Output

Infinity

 

When you divide 1 by 0, the result is Infinity because the value tends towards infinity.

 

-Infinity

-Infinity represents a value that is less than any finite number. It is the result of operations like dividing a negative number by 0.

 

negativeInfinity.js

 

let negativeInfinity = -1 / 0;
console.log(negativeInfinity); // Output: -Infinity

Output

-Infinity

When you divide -1 by 0, the result is -Infinity because the value tends towards negative infinity.

 

NaN (Not-a-Number)

NaN represents a value that is not a legal number. It is the result of operations that do not result in a valid number, such as dividing 0 by 0, or attempting to perform arithmetic on a non-numeric value.

 

not-a-number.js

let notANumber = 0 / 0;
console.log(notANumber); // Output: NaN

let invalidOperation = "hello" * 3;
console.log(invalidOperation); // Output: NaN

Output

NaN
NaN

Dividing 0 by 0 results in NaN because the operation is undefined. Multiplying a string ("hello") by a number results in NaN because the operation is invalid.

 

Infinity is a special number that represents an infinitely large value. -Infinity is a special number that represents an infinitely small (negative) value. NaN is a special value that represents an invalid or undefined numerical result. You can experiment with these values in the Node.js shell to better understand how they behave in different scenarios.

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment