In this comprehensive chapter, we'll explore the vast world of handling numbers in JavaScript. From the fundamental arithmetic operations to the advanced concepts like BigInts, we'll provide detailed explanations, practical examples, and insights to equip you with a thorough understanding of dealing with numbers in JavaScript.
JavaScript, like any other programming language, supports basic arithmetic operations that are essential for mathematical computations.
Addition is a fundamental arithmetic operation used to find the total sum of two or more numbers.
const sum = 10 + 5;
console.log(sum); // Output: 15
Subtraction is the process of finding the difference between two numbers.
const difference = 20 - 8;
console.log(difference); // Output: 12
Multiplication involves repeated addition and is used to find the product of two or more numbers.
const product = 6 * 7;
console.log(product); // Output: 42
Division is the inverse operation of multiplication and is used to distribute a quantity into equal parts.
const quotient = 100 / 10;
console.log(quotient); // Output: 10
JavaScript provides various methods and properties for more advanced numerical operations.
The Math
object in JavaScript is a treasure trove of mathematical functions and constants.
console.log(Math.sqrt(25)); // Output: 5
console.log(Math.PI); // Output: 3.141592653589793
Rounding functions are used to approximate a number to a certain precision.
console.log(Math.round(4.7)); // Output: 5
console.log(Math.floor(4.7)); // Output: 4
console.log(Math.ceil(4.3)); // Output: 5
The Math.random()
function generates a pseudo-random number between 0 (inclusive) and 1 (exclusive).
const randomNum = Math.random();
console.log(randomNum);
Introduced in ECMAScript 2020, BigInts allow handling integers of arbitrary precision, overcoming the limitations of standard JavaScript numbers.
const bigNum = 123456789012345678901234567890n;
console.log(bigNum);
BigInts support all basic arithmetic operations and can be seamlessly integrated with standard JavaScript numbers.
const bigSum = 123456789012345678901234567890n + 1n;
console.log(bigSum);
In this comprehensive exploration, we've covered a wide range of topics related to dealing with numbers in JavaScript. From basic arithmetic to advanced concepts like BigInts, you now have a solid understanding of how to handle numerical operations effectively in your JavaScript projects. Remember to practice and experiment with these concepts to reinforce your learning and discover their practical applications in real-world scenarios. Happy coding !❤️