2

In this function, it squares every number alone, and to do that it splits the number first.


I don't understand why it has to put '' before num here ('' +num).split('')

let x = (function squareDigits(num){
    return Number(('' +num).split('').map(function (val) { return val * val;}).join(''));
}(somenumber))
3
  • 4
    to convert from number to string, because you cant use .split on a number Commented Jun 22, 2020 at 22:51
  • ''+num is a way to cast a Number to a String. You could also use num.toString() if you prefer. Note that +string casts a String to a Number, as well. Commented Jun 22, 2020 at 23:01
  • It's the shortest way to convert a number to a string Commented Jun 22, 2020 at 23:24

2 Answers 2

4

'' + num converts the number into string.

See examples in code snippet below:

let num = 1;

console.log(typeof (num));
console.log(typeof ('' + num));

Sign up to request clarification or add additional context in comments.

Comments

1

''+num is a way to convert a number to its string representation. If you want an explanation of what the code is doing -- see the comments, as they are numbered.

let x = (function squareDigits(num) {
  return Number( // 5. This is redundant.  Result of 4 was already a number.  But it returns the result.
    ('' + num) // 1. Converts number to string eg. 123 => "123"
      .split('') // 2. Coverts the string to an array eg. "123" => ["1", "2", "3"]
      .map(function (val) {
        // 3. Returns an array by mapping eg. ["1", "2", "3"] => [1, 4, 9]
        return val * val; // note: * operator coerces string digits to numbers
      })
      .join('') // 4. Joins the array eg. [1, 4, 9] => 149
  );
})(somenumber);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.