How do I do a function with if/Else?

Asked

Viewed 80 times

-4

I wrote this function more gives error and I would like to understand why:

function hojeSeJoga (domingo){
  if (domingo==domingo){
    console.log("Hoje é dia de futebol")
    return true;
    } else{
      console.log("Hoje não é dia de futebol")
      return false;
      } 
  }
  • You mean that if domingo is different from domingo So it’s not football day? Something like se 1 for diferente de 1?

  • Try something like domingo === 'domingo'

  • And what value is passed in the parameter hojeSeJoga(valor aqui)? Is a string or is a numeric value, or a string in date format or is an object of new Date?

1 answer

1

You should use quotes to make this comparison. I also suggest you change the name of the function parameter to day:

function hojeSeJoga (dia){
  if (dia=="domingo"){
    console.log("Hoje é dia de futebol")
    return true;
  }else{
    console.log("Hoje não é dia de futebol")
     return false;
    } 
 }
 
 hojeSeJoga('sábado')
 hojeSeJoga('domingo')

In its original code, you do not use quotation marks, which makes the function think that the right operand of the equality operator is a variable: thus, the comparison is being if something is equal to this something, that is, it always enters the first if, independent of the value of the argument passed to the function.

  • Perfect! Just wear it "===" ;)

  • This appeared : Your solution did not pass the tests Goals that were not met: hojeSeoga makes comparisons against strings Test results: hojeSeJoga("Sunday") should say if you play See details true == 'Today is football day!!! ' hojeSeJoga("Tuesday") should say that it does not play See details false == 'Today is not football day!

  • @Renansantos With all due respect, but I’ve lost count of how many times you’ve asked this same question here, just a simple search, see <- I suggest you read them all, as well as having several answers (such as that one, for example), the conclusion that we have reached is that this site is not a very good source of study, since this "error" of "comparisons against strings" is ridiculous, as well as misrepresenting and confusing beginners.

  • For example, see this comment, that and this one too. In short, the above solution is perfectly valid. If the site requires comparisons otherwise without explaining the reason, it is not a good source of studies (because the reason depends on the context).

Browser other questions tagged

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