How does one square an array of numbers using a FOR OF loop in javascript

1.2k Views Asked by At

I am trying to square an array of numbers so that each number prints out the number multiplied by itself.

ex:

const numbers = [1,3,4,5,6,7,8,9]

for (let numb of numbers) {
numb * numb;

console.log(numb)

I am not sure what I am doing wrong here. I am doing Colt Steele's web developer boot camp on Udemy and he doesn't explain his quizzes at all he just throws one at you with little to no explanation.

2

There are 2 best solutions below

0
On

You are calculating the square of the number but you're not doing anything with it, you either have to store it into a variable or print it directly:

for (let numb of numbers) {
    const square = numb * numb;
    console.log(square)
}

or:

for (let numb of numbers) {
    console.log(numb * numb)
}
0
On

You could map the array and then output it.

const numbers = [1,3,4,5,6,7,8,9]
const squared = numbers.map(num => num * num)

console.log(squared) // Array of squared numbers.

Or, you could then loop this and print out one-by-one.

for (const square of squared) {
  console.log(square)
}