Why do we put ' ' before the .split function in javascript

Viewed 228

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))
2 Answers

'' + num converts the number into string.

See examples in code snippet below:

let num = 1;

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

''+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);
Related