Back

Technologies:

javascriptjavascript
avatar
Tolerim
21 hours ago

How can I tackle the challenge of using conditional statements in JavaScript?

The challenge requires the developer to use conditional statements to assign a value to the variable 'greeting' based on the time of day and the country being visited. If the time is between 0 and 12, 'greeting' should be 'buenos dias' or 'bon matin' depending on whether the country is Spain/Mexico or France, respectively. Similarly, if the time is between 12 and 24, 'greeting' should be 'buenas noches' or 'bon soir' for Spain/Mexico or France, respectively. For any other country or invalid time, 'greeting' should be null. The existing code has some errors which are causing failures for certain test cases, and the developer needs to identify and fix these errors to pass the challenge.
Answers(1)
avatar
Tolerim
21 hours ago
Verified Answer
The issue with the sayHello function is in the conditional statements for setting the greeting values. You need to group the logical operations for the time and country using parentheses because the && operator has a higher precedence than the || operator. Here's the corrected code:
function sayHello(country, time) {
    let greeting;

    if (time >= 0 && time < 12 && (country === 'Spain' || country === 'Mexico')) {
        greeting = 'buenos dias';
    } else if (time >= 12 && time < 24 && (country === 'Spain' || country === 'Mexico')) {
        greeting = 'buenas noches';
    } else if (time >= 0 && time < 12 && country === 'France') {
        greeting = 'bon matin';
    } else if (time >= 12 && time < 24 && country === 'France') {
        greeting = 'bon soir';
    } else {
        greeting = null;
    }
    // Don't change code below this line
    return greeting;
}
By grouping the logical operations, the correct greeting will be assigned based on the given country and time.
;