I am practicing my javascript on codewars, and I keep getting a “NaN” at the end of my answer whenever I run my code. Can’t seem to figure what is wrong. Here is my code and the information on the problem. Appreciate the help!
const squareDigits = (num) => {
let numStr = num.toString().split(" ");
let newNum = " ";
for(let i = 0; i <= numStr.length; i++){
newNum += numStr[i] * numStr[i];
}
return newNum;
}
squareDigits(12345);
Welcome. In this kata, you are asked to square every digit of a number.
For example, if we run 9119 through the function, 811181 will come out, because 92 is 81 and 12 is 1.
Note: The function accepts an integer and returns an integer
you can’t multiply two strings - you are converting the number to string to separate the digits but you are never converting it back to a number to do the math operation
you are splitting on a space, your string doesn’t have spaces (hint to make it more efficient: you don’t need to use split and then the loop)
the string newNum has also a space as starting value
suggestion for debugging:
console.log the hell out of everyone of your variables, every time it is changed, log it to the console
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.
See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.