Home Web Front-end JS Tutorial Math Namespace & BigInt

Math Namespace & BigInt

Sep 13, 2024 pm 10:19 PM

Math Namespace & BigInt

Math.sqrt i.e sqrt is a part of Math namespace.

// 2 ways to get square root.
Math.sqrt(100); // 10, Method 1
100*(1/2); // 10, Method 2
8
*(1/3); // 2, works for cubic root also

Math.max() & Math.min():

Math.max(23,54,12,6,32,98,87,34,11); // 98
// Does type coercion also
Math.min(23,54,12,'6',32,98,87,34,11); // 6
// Does not do parsing
Math.min(23,54,12,'6px',32,98,87,34,11); // NaN

Inbuilt constants on Math object:

Math.PI * (Number.parseFloat('10px')**(2)); // Getting area

Generate a no b/w 1-6:

Math.trunc(Math.random() * 6) 1;

Generatate a random no b/w an upper-lower limit:

const randomInt = (min, max) => Math.floor(Math.random() * (max-min)) 1 min;
randomInt(10,20);

// All of these Math.method() do type coercion.
Math.trunc(25.4); // 25
Math.round(25.4); // 25
Math.floor(25.4); // 25
Math.ceil(25.4); // 26

Math.floor is a better choice for negative numbers.

Math.trunc(-25.4); // -25
Math.floor(-25.4); // -26

// Rounding decimals: .toFixed returns a string, not a number
(2.5).toFixed(0); // '3'
(2.5).toFixed(3); // '2.500'
(2.345).toFixed(2); // '2.35'

// Add a unary sign to convert it to a no.
(2.345).toFixed(2); // 2.35

// Number is a primitive, hence they don't have methods. SO behind the scene, JS will do boxing, i.e transform primitive into a no object, perform the operation and then when operation is finished, transform it back to primitive.

Modular or Remainder Operator:

5 % 2; // 1

8 % 3; // 2
8 / 3; // 2.6666666666666665

// Odd or Even
const isEven = n => n%2 === 0;
isEven(20);
isEven(21);
isEven(22);

Usecase: Used to work with all odd rows, even rows, nth time etc.

Numeric Separators: [ES2021]

Used for representing really large numbers
These are underscores which can be placed between numbers. The engine ignores these underscores, its reduces the confusion for devs.
Ex. const diameter = 287_460_000_000;
diameter; // 287460000000

const price = 342_25;
price; // 34225

const fee1 = 1_500;
const fee2 = 15_00;
fee1 === fee2; // true

Underscore can be placed ONLY between numbers.
It cannot be placed adjacent to a dot of decimal.
It also cannot be placed at the begining or the end of the no.

const PI = 3.14_15;
PI; // 3.1415

All are invalid example of numeric separators

const PI = 3.1415; // Cannot be placed in the begining.
const PI = 3.1415
; // Cannot be placed in the end.
const PI = 3_.1415; // Cannot be placed adjacent to a decimal dot.
const PI = 3.1415; // Cannot be placed adjacent to a decimal dot.
const PI = 3.
_1415; // Two in a row cannot be placed.

Converting Strings to Numbers:

Number('2500'); // 2500
Number('25_00'); // NaN , Hence we can only use when directly numbers are assigned to a variable. Hence, if a no is stored in the string or getting a no from an API, then to avoid error don't use '_' numeric separator.
Similar goes for parseInt i.e anything after _ is discarded as shown below:
parseInt('25_00'); // 25

BigInt

Special type of integers, introduced in ES2020
Numbers are represented internally as 64 bits i.e 64 1s or 0s to represent any number. Only 53 are used to store the digits, remaining are used to store the position of decimal point and the sign. Hence, there is a limit on the size of the number i.e ((2*53) - 1). This is the biggest no which JS can safely represent. The base is 2, because we are working in binary form while storing.
2
*53 - 1; // 9007199254740991
Number.MAX_SAFE_INTEGER; // 9007199254740991

Anything larger than this is not safe i.e it cannot be represented accurately. Precision will be lost for numbers larger than this as shown in last digit. Sometimes it might work, whereas sometimes it won't.
Number.MAX_SAFE_INTEGER 1; // 9007199254740992
Number.MAX_SAFE_INTEGER 2; // 9007199254740992
Number.MAX_SAFE_INTEGER 3; // 9007199254740994
Number.MAX_SAFE_INTEGER 4; // 9007199254740996

Incase we get a larger no from an API larger than this, then JS won't be able to deal with it. So to resolve the above issue, BigInt a new primitive data type was introduces in ES2020. This can store integers as large as we want.

An 'n' is added at the end of the no to make it a BigInt. Ex.
const num = 283891738917391283734234324223122313243249821n;
num; // 283891738917391283734234324223122313243249821n

BigInt is JS way of displaying such huge numbers.
Another way using Constructor Fn for creating BigInt number.
const x = BigInt(283891738917391283734234324223122313243249821);
x; // 283891738917391288062871194223849945790676992n

Operations: All arithmetic operators work the same with BigInt;
const x = 100n 100n;
x; // 200n

const x = 10n * 10n;
x; // 100n

Avoid mixing BigInt numbers with regular numbers

const x = 100n;
const y = 10;
z = x*y; // Error

To make it work, use BigInt constructor Fn:
z = x * BigInt(y);
z; // 1000n

Exception to it are comparsion operators & unary operator.

20n > 19; // true
20n === 20; // false, === prevents JS from doing type coercion. Both the LHS & RHS have different primitive types, hence results in 'false'.

typeof 20n; // 'bigint'
typeof 20; // 'number'

20n == 20; // true, as JS does type coercion to compare only the values and not the types by converting BigInt to a regular number.
Same goes for this also: 20n == '20'; // true

Exception:

BigInt number is not converted to string on using operator.
const num = 248923874328974239473829n
"num is huge i.e. " num; // 'num is huge i.e. 248923874328974239473829'

Note:
Math.sqrt doesn't work with BigInt.
During division of BigInts, it discards the decimal part.
10 / 3; // 3.3333333333333335
10n / 3n; // 3n
12n / 3n; // 4n

This new primitive type adds some new capabilities to JS language to make it work with huge no.

The above is the detailed content of Math Namespace & BigInt. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles