skip to Main Content

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


  1. join doesn’t mutate the variable it operates on, but creates a new string.

    Number(arr.join("")) // NOT doing anything to the arr variable here,
                         // the evaluated expression isn't assigned to anything
    
    return arr // the unchanged value of arr is returned
    

    But you can simply put the return statement on the line before:

    return Number(arr.join(""));
    
    Login or Signup to reply.
  2. Number does not modify the original variable, so it must process directly as an expression i.e.:

    return Number(arr.join(""));
    

    or stored in a variable:

    let result = Number(arr.join(""));
    
    Login or Signup to reply.
  3. As CBroe pointed out in the comment you need to return the value because Number(arr.join("")) does not change the arr.

    You could write your function without defining any variables using map instead of foreach and return your result like so

    function squareDigits(num){
      return num.toString().split('').map(number => number * number).join('');
    }
    
    console.log(squareDigits(232))

    This work because map is almost like foreach with the difference that it returns whatever you do inside

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search