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

Coding for Kids

What is coding? In coding we build a program to do a specific task for us. Code: A code is a set of computer instructions and when you will ...