Function to compute square of each array element in JavaScript

Took 1 minute and 53 seconds to code method that returns square of each element of the array in JavaScript. Here is the code snippet.

Code:

arr = [1, 2, 3, 4];
function square(arr) {
var arr2 = [];
for (var i = 0; i < arr.length; i++) {
arr2.push(arr[i] * arr[i]);
}
return arr2;
}

document.write(square(arr));

Result:

1,4,9,16

No comments:

Post a Comment

GITEX Dubai Talk by Saion Gupta and Saiasmi Gupta

Good morning, everyone. I'm Saion Gupta, the Founder of 10xCoderKids and the Guinness World Record holder for the youngest computer prog...