I´m a beginner in JS. I’m trying to write a function that would raise an array for particular exponent. For example, that the function raiser([2, 5, 10], 2); would output 4, 25, 100. I tried to write this function:
function raiser(numbers, exponent) {
for (let i = 0; i < numbers.length; i++) {
return console.log(Math.pow(numbers[i], exponent));
}
}
raiser([2, 5, 10], 2);
But I don´t understand what is wrong, because as a result I get only first digit of the array (output – 4). What I´m doing wrong?
Your return statement is within the for loop which is causing the problem. Just remove the return statement as you already have used console.log to print the result one by one in the loop.
Your Code:
function raiser(numbers, exponent) {
for (let i = 0; i < numbers.length; i++) {
return console.log(Math.pow(numbers[i], exponent));
}
}
raiser([2, 5, 10], 2);
Correction:
function raiser(numbers, exponent) {
for (let i = 0; i < numbers.length; i++) {
console.log(Math.pow(numbers[i], exponent));
}
}
raiser([2, 5, 10], 2);
You can also save it in an array and return it.
function raiser(numbers, exponent) {
let temp = []
for (let i = 0; i < numbers.length; i++) {
temp.push(Math.pow(numbers[i], exponent));
}
return temp
}
console.log(raiser([2, 5, 10], 2));
I use ES6 shorthand mostly, so I would write it as:
const raiser = (a,e) => a.map(i => i**e)
console.log(raiser([2, 5, 10], 2));