Skip to content Skip to sidebar Skip to footer

Square Each Number In An Array In Javascript

I'm trying to square each number in an array and my original code didn't work. I looked up another way to do it, but I'd like to know WHY the original code didn't work. Original co

Solution 1:

Math.sqrt gives you square root not square of a number. Use Math.pow with second argument of 2.

Solution 2:

How about that ?

function (arr) {
  return arr.map(function (x) {
    returnMath.pow(x, 2);
  });
}

Array.map(func) applies the function to each element of the map and returns the array composed of the new values. Math.pow(base, exp) raises base to its exp power.

Solution 3:

The first sample is taking the square root, not squaring the value. To square you want to use

Math.pow(arr[i],2);

Solution 4:

Here is the function write with ES6Exponentiation (**):

let arr = [1, 6, 7, 9];
let result = arr.map(x => x ** 2);
console.log(result);

Solution 5:

The original code is taking the square root of the value. The second version is multiplying the value with itself (squaring it). These are inverse operations

Post a Comment for "Square Each Number In An Array In Javascript"