Why does my function only return "even"?

Asked

Viewed 68 times

-3

 function parimp(n){
         for(var i = 0; i <= n; i++){
             if(i % 2 == 0){
                 return "par";
             }else{
                 return "impar";
             }
         }
     }
     
      var s = parimp(25);
      console.log(s);

1 answer

4


Because that’s what you had done. One return serves to terminate the function, if you did not want it to be closed do not put a return.

Maybe I wanted to do this:

function parimp(n) {
    for (var i = 0; i <= n; i++) console.log(i % 2 == 0 ? "par" : "impar");
}
parimp(25);

Or better yet:

function parimp(n) {
    for (var i = 0; i <= n; i += 2) console.log("par\nimpar");
}
parimp(25);

I put in the Github for future reference.

If the number is fixed at 25 you can simplify even more.

  • Got it. Return closes the function. Thanks :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.