Animations

API

Arrays

Async

Basics

Challenges

Classes

Console

Dates

Debugging

DOM Elements

DOM Methods

DOM Navigation

DOM Properties

Event Listeners

Flow Control

Forms

Functions

Global Functions

JSON

Keywords

Libraries (3rd party)

Math

Modules

Objects

Snippets

String

Types

Widgets

Window Object

JavaScript - Number

JavaScript has only one type of number. JavaScript numbers can be written with, or without decimals.

JavaScript numbers are always 64-bit floating point.

Infinity: Infinity (or -Infinity) is the value JavaScript will return if you calculate a number outside the largest possible number. Division by 0 (zero) also generates Infinity. Infinity is a number: typeOf Infinity returns number.

    
var x = 2 / 0;      // x will be Infinity
var y = -2 / 0;     // y will be -Infinity

typeof Infinity; // returns "number"

NaN: NaN is a JavaScript reserved word indicating that a value is not a number. Trying to do arithmetic with a non-numeric string will result in NaN (Not a Number).

var x = 100 / "Apple"; // x will be NaN (Not a Number)

Numbers as Objects: Normally JavaScript numbers are primitive values created from literals: var x = 123. But numbers can also be defined as objects with the keyword new: var y = new Number(123).

Don't create Number objects. It slows down execution speed. Just remember, numbers as OBJECTS are not the same as Number Types (primitive data type).


var x = 500;
var y = new Number(500);
// (x == y) is true because x and y have equal VALUES
// (x === y) is false because x and y have different types

Misunderstanding Floats: All numbers in JavaScript are stored as 64-bits Floating point numbers (Floats). All programming languages, including JavaScript, have difficulties with precise floating point values.


var x = 0.1;
var y = 0.2;
var z = x + y       // the result in z will not be 0.3
if (z == 0.3)       // this if test will FAIL

To solve the problem above, it helps to multiply and divide.


var z = (x * 10 + y * 10) / 10;             // z will be 0.3
if (z == 0.3)                               // this if test will PASS