dimanche 9 février 2020

Curly braces breaking if statement, why? [duplicate]

I always thought that having curly braces in if statement is considered a best practice, i.e.: Is it a bad practice to use an if-statement without curly braces?

The following code gives timeout in codewars and blocks Chrome console:

function sumDigPow(a, b) {
    var answer = [];
    while(a<=b){
       if( a.toString().split('').reduce((x,y,i) => x + (+y)**(i+1),0) == a) {
         answer.push(a);
         a++;     
       }
    }
    return answer;
  }

Chrome console is blocked in a funny way, it does not give any error, but does not return result and does not accept a new command. This is the output from the codewars: Exit Code: 1 Test Results: STDERR Execution Timed Out (12000 ms)

The same code without curly braces after if statement works just fine:

function sumDigPow(a, b) {
var answer = [];
while(a<=b){
   if( a.toString().split('').reduce((x,y,i) => x + (+y)**(i+1),0) == a) 
     answer.push(a);
     a++;     

}
return answer;

}

What would be the reason for such behavior?

Aucun commentaire:

Enregistrer un commentaire