JavaScript for Beginners
About Lesson

Number in JavaScript can be written with or without decimals. JavaScript numbers can be written as:

let x = 3;     // an integer
let y = 3.14;  // a floating-point number

 

Special Number Values

JavaScript has a few special numeric values including Infinity-Infinity, and NaN (Not a Number).

let x = 2 / 0;       // x will be Infinity
let y = -2 / 0;      // y will be -Infinity
let z = Math.sqrt(-1); // z will be NaN

 

Numeric Operations

JavaScript supports several arithmetic operations including addition (+), subtraction (-), multiplication (*), division (/), modulus (%), increment (++), and decrement (--).

let x = 5 + 2;    // x will be 7
let y = 5 - 2;    // y will be 3
let z = 5 * 2;    // z will be 10
let a = 5 / 2;    // a will be 2.5
let b = 5 % 2;    // b will be 1
let c = 5; c++;   // c will be 6
let d = 5; d--;   // d will be 4

 

The Math Object

JavaScript provides a built-in Math object that has properties and methods for mathematical constants and functions.

let x = Math.PI;            // x will be 3.141592653589793
let y = Math.sqrt(16);      // y will be 4
let z = Math.abs(-5.5);     // z will be 5.5
let a = Math.ceil(0.6);     // a will be 1
let b = Math.floor(0.6);    // b will be 0
let c = Math.pow(2, 3);     // c will be 8
let d = Math.min(0, 150, 30, 20, -8, -200);  // d will be -200
let e = Math.max(0, 150, 30, 20, -8, -200);  // e will be 150
let f = Math.random();      // f will be a random number

 

Numbers are a powerful tool in JavaScript, allowing you to manipulate and interact with numerical data. They are a fundamental concept that’s widely used in programming, so understanding how they work will greatly enhance your JavaScript coding skills.