New Math Methods
ES6 added the following methods to the Math object:
- Math.trunc() Method: It removes decimal fractions, returning the integer part of a number, effectively truncating it.
- Math.sign() Method: It returns the sign of a number as 1 (positive), -1 (negative), or 0 (zero).
- Math.cbrt() Method: It calculates the cubic root of a number, returning the value that, when cubed, equals the input.
- Math.log2() Method: It computes the base-2 logarithm of a positive number, indicating the power of 2 needed to obtain the input.
- Math.log10() Method: It calculates base-10 logarithm of a positive number, representing power of 10 for the input.
Example: Here we are use Math.trunc() and Math.sign() method.
Javascript
const num1 = [4.9, -7.2, 16, -25, 30, 100]; const truncatedNumbers = num1.map(num => Math.trunc(num)); console.log( "Truncated:" , truncatedNumbers); const signValues = num1.map(num => Math.sign(num)); console.log( "Sign:" , signValues); |
Output
Truncated: [ 4, -7, 16, -25, 30, 100 ] Sign: [ 1, -1, 1, -1, 1, 1 ]
Example 2: In this example we are using Math.cbrt(),Math.log2() and Math.log10().
Javascript
const num2 = [8, -27, 16]; const cbrtRoots = num2.map(num => Math.cbrt(num)); console.log( "Cubic Roots:" , cbrtRoots); const log2Values = num2.map(num => Math.log2(Math.abs(num))); console.log( "Log base 2:" , log2Values); const log10Values = num2.map(num => Math.log10(Math.abs(num))); console.log( "Log base 10:" , log10Values); |
Output
Cubic Roots: [ 2, -3, 2.5198420997897464 ] Log base 2: [ 3, 4.754887502163468, 4 ] Log base 10: [ 0.9030899869919435, 1.4313637641589874, 1.2041199826559248 ]
JS 2015 or ECMAScript 6 (ES6)
JS 2015 (ES6) also known as ECMAScript 6 (ES6), ECMAScript 6 (ES6) is a significant update to JavaScript, introducing arrow functions, classes, template literals, let and const for variable declaration, enhanced object literals, destructuring, and more modern features for better code organization and readability.