Number in JavaScript
When learning or working with JavaScript, familiarity with number-related methods and mathematical operations proves invaluable. This article will explore key methods in this domain.
To define a Number the most simple syntax is
const score = 400
console.log(score);
In this part of the code:
const score
: Declares a constant variable namedscore
.= 400
: Assigns the value400
to thescore
variable.console.log(score)
: Prints the value of thescore
to the console. In this case, it will print400
.
So, score
is a primitive data type (number) and is assigned a literal value of 400
.
const balance = new Number(100)
console.log(balance);
In this part of the code:
const balance
: Declares a constant variable namedbalance
.new Number(100)
: Creates a new Number object with an initial value of100
and assigns it to thebalance
variable.console.log(balance)
: Prints the value ofbalance
to the console. In this case, it will print the Number object, not just the primitive value.
Now, let's understand the difference between the two codes:
Primitive vs. Object:
In Code 1,
score
is a primitive number type. Primitives are immutable and passed by value.In Code 2,
balance
is an instance of the Number object created using thenew
keyword. Objects are mutable and passed by reference.
Value Representation:
When you log
score
, it directly prints the primitive value400
.When you log
balance
, it prints the entire Number object, which might look like: [Number: 100].
Usage:
Primitives (like
score
) are generally used for simple values and operations.Objects (like
balance
) are used when you need to work with methods and properties associated with the data type, or if you need to pass around mutable references.
Methods that we get with Numbers
In JavaScript, a "Number" is a basic thing for handling numbers. It can be a regular number, like 42, or a special "Number" object. Here are some tricks (methods) you can do with numbers:
Turning Numbers into Text:
.toString()
: Imagine you have the number 42, and you want to treat it like words. This method makes it "42" in text form.const num = 42; const strNum = num.toString(); // Result: "42"
Controlling Decimals:
.toFixed(digits)
: If you have a number like 3.14159 and you only want two digits after the dot, this trick turns it into "3.14".const num = 3.14159; const formattedNum = num.toFixed(2); // Result: "3.14"
Scientific Notation:
.toExponential(digits)
: For really big or really small numbers, like 12345, this trick makes it look like "1.23e+4".const num = 12345; const expNum = num.toExponential(2); // Result: "1.23e+4"
Fancy Precision:
.toPrecision(digits)
: If you want control over how many significant digits (important numbers) to show, this helps. For example, "12345.6789" could become "12345.7". And returns value in string format.const otherNumber = 12345.6789; console.log(num.toPrecision(6)); // Result: "12345.7" const otherNumber = 123.8966; console.log(otherNumber.toPrecision(3)); //Result: 124 const otherNumber = 1123.8966; console.log(otherNumber.toPrecision(3)); //Result: 1.12e+3
Getting the Basic Number Back:
.valueOf()
: If you've been playing with a special "Number" object, this gets you back to the simple number. If you hadnew Number(42)
, this gets you just42
.const numObj = new Number(42); const primitiveValue = numObj.valueOf(); // Result: 42
Checking If It's Not a Number (NaN):
isNaN()
: Checks if a value is NaN (Not a Number).isNaN(42); // Result: false isNaN("foo"); // Result: true
Checking If It's a Real Number:
isFinite()
: If you want to know if a number isn't something weird like infinity (too big) or not a number at all, this helps.isFinite(42); // Result: true isFinite(Infinity); // Result: false
Reading Numbers From Text:
parseInt("42")
andparseFloat("3.14")
: If you have numbers hiding in text, these tricks can find them and turn them into real numbers.parseInt("42"); // Result: 42 parseFloat("3.14"); // Result: 3.14
Representing Numbers in Some Country-Specific Systems
toLocalString():
Returns a string with a language-sensitive representation of the number.
const hundreds = 1000000;
console.log(hundreds.toLocaleString("en-IN")); //Result: 10,00,000
console.log(hundreds.toLocaleString("en-US")); //Result: 1,000,000
Maths in JavaScript
In JavaScript, the Math
object provides a set of properties and methods for performing mathematical operations.
Mathematical Constants:
console.log(Math.PI); // Pi (π)
console.log(Math.E); // Euler's number (e)
Basic Mathematical Operations:
javascriptCopy codeconsole.log(Math.abs(-5)); // Absolute value
console.log(Math.round(4.7)); // Round to the nearest integer
console.log(Math.floor(4.7)); // Round down to the nearest integer
console.log(Math.ceil(4.2)); // Round up to the nearest integer
console.log(Math.max(1, 2, 3)); // Maximum of a list of values
console.log(Math.min(1, 2, 3)); // Minimum of a list of values
Exponential and Logarithmic Functions:
javascriptCopy codeconsole.log(Math.pow(2, 3)); // Exponentiation: 2^3
console.log(Math.sqrt(9)); // Square root: √9
console.log(Math.exp(2)); // Exponential function: e^2
console.log(Math.log(8)); // Natural logarithm: loge(8)
console.log(Math.log10(100)); // Base-10 logarithm: log10(100)
Trigonometric Functions:
javascriptCopy codeconsole.log(Math.sin(Math.PI / 2)); // Sine of π/2
console.log(Math.cos(Math.PI)); // Cosine of π
console.log(Math.tan(Math.PI / 4)); // Tangent of π/4
console.log(Math.asin(1)); // Arcsine, returns radians
console.log(Math.acos(0)); // Arccosine, returns radians
console.log(Math.atan(1)); // Arctangent, returns radians
Random Number Generation:
javascriptCopy codeconsole.log(Math.random()); // Random number between 0 (inclusive) and 1 (exclusive)
console.log(Math.floor(Math.random() * 10) + 1); // Random integer between 1 and 10
What if we want a random number between minimum and maximum value
const min = 10
const max = 20
console.log(Math.floor(Math.random() * (max - min + 1)) + min) //Result Any random numver between 10 and 20
Degrees to Radians and Radians to Degrees:
javascriptCopy codeconst degrees = 45;
const radians = (degrees * Math.PI) / 180;
console.log(radians); // Conversion from degrees to radians
const radiansValue = Math.PI / 4;
const degreesValue = (radiansValue * 180) / Math.PI;
console.log(degreesValue); // Conversion from radians to degrees