I was doing a codewars challenge where I had to make a program that will turn a certain set of numbers to the square of those numbers. So for example, let’s say the number given is 232. What I have to do is split those 3 numbers and give the square to each individual number. So the eventual answer for 232 in this case will be 494 as 2 square is 4 and 3 square is 9. I completed the challenge with this code
function squareDigits(num){
let numStr = String(num)
let split = numStr.split("");
let arr = [];
for(let i = 0; i <= split.length-1; i++){
let sqr = Math.pow(split[i],2);
arr.push(sqr);
}
let join = Number(arr.join(""));
return join
}
console.log(squareDigits(232))
The line of code after my for loop indicates that after the numbers were squared, it would be joined together to make it one number. My issue came when I didn’t make a new variable and directly wrote Number(arr.join(""))
and return the variable arr
. The result was that the numbers did NOT become 1 whole number and it was still seperated.
The code before making a new variable:
function squareDigits(num){
let numStr = String(num)
let split = numStr.split("");
let arr = [];
for(let i = 0; i <= split.length-1; i++){
let sqr = Math.pow(split[i],2);
arr.push(sqr);
}
Number(arr.join(""));
return arr
}
console.log(squareDigits(232))
Why do I have to make a variable before the code will work
3
Answers
join
doesn’t mutate the variable it operates on, but creates a new string.But you can simply put the return statement on the line before:
Number does not modify the original variable, so it must process directly as an expression i.e.:
or stored in a variable:
As CBroe pointed out in the comment you need to return the value because
Number(arr.join(""))
does not change thearr
.You could write your function without defining any variables using map instead of foreach and return your result like so
This work because map is almost like foreach with the difference that it returns whatever you do inside