JavaScript Math.cbrt() Method

JavaScript Math.cbrt() is a built-in function that is used to find the cube root of a number. The function accepts a single parameter, simply a number whose cube root needs to find. It returns a cube root of the given number.

Syntax

``Math.cbrt(x)``

Parameter(s)

The variable x, whose cube root value is to be determined.

Return Value

The cube root value.

Example 1

See the following code.

``````var a = 8;
var b = 27;
var c = 64;
var d = -64;

console.log(Math.cbrt(a));
console.log(Math.cbrt(b));
console.log(Math.cbrt(c));
console.log(Math.cbrt(d));``````

Output

``````2
3
4
-4``````

Example 2

The following example demonstrates a case where values other than valid numbers are passed.

``````var a = "Hello, world";
var b;

console.log(Math.cbrt(a));
console.log(Math.cbrt(b));``````

Output

``````NaN
NaN``````

Example 3

``````console.log(Math.cbrt(2 + i));
``````

Output

``ReferenceError: i is not defined``

Example 4

The following example demonstrates the use of polyfill for the cbrt() method.

``````var a = 8;
var b = 27;
var c = 64;
var d = -64;

function polyfill(x) {
return Math.round(x < 0 ? -Math.pow(-x, 1 / 3) : Math.pow(x, 1 / 3));
}

console.log(Math.cbrt(a));
console.log(Math.cbrt(b));
console.log(Math.cbrt(c));
console.log(Math.cbrt(d));
console.log();

console.log(polyfill(a));
console.log(polyfill(b));
console.log(polyfill(c));
console.log(polyfill(d));``````

Output

``````2
3
4
-4

2
3
4
-4``````

That’s it.

This site uses Akismet to reduce spam. Learn how your comment data is processed.