0

The challenge is to keep on adding up all the digits of a number until it is a single digit. For the solution there is plus signs before the variables, which I have never seen before. Also if you remove it, it will return an error.

function additivePersistence(n) {
    let count=0;
    while(String(n).length>1){
        n=[...String(n)].reduce((a, b)=>+a + +b);
        count++;
    }
    return count;
}

Can someone explain to me what that is doing"

GhostRoboXt
  • 29
  • 1
  • 10
  • Does this answer your question? [Explain +var and -var unary operator in javascript](https://stackoverflow.com/questions/12120802/explain-var-and-var-unary-operator-in-javascript), and **better ones**: [What is the purpose of a plus symbol before a variable?](https://stackoverflow.com/q/6682997/4642212), [What does = +\_ mean in JavaScript](https://stackoverflow.com/q/15129137/4642212). – Sebastian Simon Jul 26 '20 at 00:41
  • See [What does this symbol mean in JavaScript?](https://stackoverflow.com/q/9549780/4642212) and the documentation on MDN about [expressions and operators](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators). – Sebastian Simon Jul 26 '20 at 00:41

2 Answers2

1

This is to cast variable as number.

8HoLoN
  • 970
  • 1
  • 12
0
+a // + is used to be sure that a is a number before adition
+ // is plus sign for adition!
+b // + here is used to  be sur that b is number before adition

if we were sure that a and b are numbers (there where no need for that)

//you can replace + sign with
parseInt(a) + parseInt(b)
//or
parseFloat(a) + parseFloat(b)

as an examlpe imagine what hepens if you forget the + sign

"1" + 1 = "11"
//but
+"1" + 1 = 2
phoenixstudio
  • 928
  • 1
  • 5
  • 15