Search code examples
javascriptif-statementboolean-logicboolean-expression

Trouble with boolean logic in if (else) statements


I am trying to create a function that returns a different greeting depending on two variables: the country and time provided.
If time is greater than or equal to 0 but less than 12 it will be morning. And if time is greater than or equal to 12 but less than 24 it will be evening (so morning is false).
If country is Spain or Mexico and morning is true then "buenos dias" should be printed, if country is Spain or Mexico but morning is false (in the evening) then "buenos noches" should be printed.
Similarly for when the country is France.
Currently Spain is the only one that works correctly.

Examples that do not work:

  • evening for Mexico prints "buenos dias"
  • evening for France prints null.


function sayHello(country, time) {
  let greeting;
  let morning; 
  if(time>=0 && time<12){
      morning= true; 
  }else if(time>=12 && time <24){
      morning = false; 
  } else {
      morning = null; 
  };

  if(morning && country === 'Spain'|| country==='Mexico'){
    greeting = 'buenos dias';
  } else if (!morning && country === 'Mexico'|| country==='Spain'){
    greeting = 'buenos noches';
  } else if(morning && country==='France'){
    greeting = 'bon matin';
  } else if(!morning && country==='France'){
    greeting = 'bon soir';
  } else{
    greeting = null; 
  }

  // Don't change code below this line
  return greeting;
}

console.log(sayHello('Mexico', 15));

Solution

  • You need ( ) in your boolean statements like this one:

      if(morning && country === 'Spain'|| country==='Mexico'){
    

    to turn it into

      if(morning && (country === 'Spain'|| country==='Mexico')){
    

    and the logic will change.

    You can't just write one long line of boolean expressions, you need to express "IF morning == true AND (country == 'Spain' OR country == 'Mexico') "

    Then apply this to the other if and else if statements until you are done.