froggyguts froggyguts - 2 months ago 14
Javascript Question

function that squares the values in an array

i've been instructed to create a function that takes values from an array and squares each value, and logging the numbers to the console. i've attempted two methods, neither of which work so far:

first attempt:

var numbers = [2, 7, 13, 24];

function squareAll(numbers) {
var newArray = [];
for(i = 0; i < numbers.length; i++) {
numbers = newArray.push(Math.pow(numbers[i], 2))
return newArray;
}
console.log(squareAll(numbers));
}


second attempt:

var numbers = [2, 7, 9, 25];
var newArray = [];
var squareAll = function(numbers) {
for(var i = 0; i < numbers.length; i++){
newArray = [];
newArray.push(squareAll[i] * squareAll[i])
};
return newArray;
};
console.log(squareAll(newArray));


when i try both codes in the javascript console, both return undefined and won't give me a specific error so i'm unsure what's wrong here. any explanation would be appreciated!

Answer

In your first attempt you are assigning a push method into a variable, which is a bad practice. Secondly, you are returning the function just right after the first cycle of the loop, so you are stopping the loop before going through all the elements of the array.

And in the second attempt, you are basically clearing the array after each cycle of the loop, because of the newArray = []; inside the loop. So with every cycle, you are dropping an element inside the newArray and then you are telling the loop to clear the newArray. The loop will become infinite, because the length of the newArray will never reach the numbers.length.

var numbers = [2, 7, 13, 24];
var newArray = [];

console.log(numbers.map(v => Math.pow(v, 2)));

Or:

var numbers = [2, 7, 13, 24];
var newArray = [];

for (var i = 0; i < numbers.length; i++) {
  newArray.push(Math.pow(numbers[i], 2));
}

console.log(newArray);