Siawash Kasra
Siawash Kasra

Reputation: 81

Switch statement doesn't return the desired value

I am trying to return 'Can drink' or 'Wait' based on the ages array but something is wrong with my switch statement, I am getting 'Try again'.

var yearsArr = [1992, 1980, 2004, 2010];

function getAge(arr, fn) {
    var arrRes = [];
    for(var i = 0; i < arr.length; i++) {
        arrRes.push(fn(arr[i]));
    }
    return arrRes;
}

function calcAge(el) {
    return 2019 - el;
}

var ages = getAge(yearsArr, calcAge);
console.log(ages);

function canDrink(el) {
    switch(el) {
        case el >= 18:
            return 'Drink'
        break;
        case el < 18:
            return 'Wait'
        break;
        default:
            return 'Try again!'
    }
}

var drinkArr = getAge(ages, canDrink);
console.log(drinkArr);
// result = ["Try again!", "Try again!", "Try again!", "Try again!"]

Upvotes: 2

Views: 79

Answers (3)

Kriszti&#225;n Balla
Kriszti&#225;n Balla

Reputation: 20371

I would use an if/else statement instead of a switch in this case. :-)

// Returns the age for a birthYear
function getAge(birthYear) {
    return (new Date()).getFullYear() - birthYear;
}

// Returns the tapper's response for an age value
function getTapperResponse(age) {
    if (age >= 18) {
        return 'Drink';
    } else {
        return 'Wait';
    }
}

const birthYears = [1992, 1980, 2004, 2010];

const ages = birthYears.map(by => getAge(by));
console.log(ages);

const tapperResponses = ages.map(a => getTapperResponse(a));
console.log(tapperResponses);

Upvotes: 3

Nina Scholz
Nina Scholz

Reputation: 386680

You need to use true as value to check with the results of the case parts.

switch (true) {    // <---------------------for--+
    case el >= 18: // -> returns a boolean value-+

Upvotes: 4

qelli
qelli

Reputation: 2077

You are not comparing correct values in your switch statement.

Lets imagine using some values, we call canDrink with parameter 17.

function canDrink(el) { //Receives 17
    switch (el) { //Handles 17 as main value
        case el >= 18: // 17 >= 18 is false, but true===17 is false
            return 'Drink'
            break;
        case el < 18: // 17<18 is true, but false===17 is false
            return 'Wait'
            break;
        default: // So, none of the conditions matches default executes.
            return 'Try again!'
    }
}

How should you adapt this?

function canDrink(el) { // el = 17
    switch (true) { // We use true as our main value
        case el >= 18: // 17>=18 is false, so our main value true === false, not executed
            return 'Drink'
            break;
        case el < 18: // 17<18 is true, so true===true, executes this.
            return 'Wait'
            break;
        default:// No need for default.
            return 'Try again!'
    }
}

You can check this working example.

Upvotes: 3

Related Questions