DEV Community

German Gamboa
German Gamboa

Posted on • Originally published at germangamboa.com on

Javascript check for values

I forgot where I saw this a while back but I wanted to documented here for anyone who might find it helpful (future me).

So when you have to check a value against other values rather than doing a bunch of if else statements

const value_to_check: string = "purple";

if ("green" === value_to_check) {
    // do the thing
} else if ("red" === value_to_check) {
    // do the thing
} else if ("blue" === value_to_check) {
    // do the thing
}

Enter fullscreen mode Exit fullscreen mode

or doing a switch statement

const value_to_check: string = "purple";

switch (value_to_check) {
    case "red":
        // do the thing
        break;
    case "green":
        // do the thing
        break;
    case "blue":
        // do the thing
        break;
    default:
    // do the thing
}

Enter fullscreen mode Exit fullscreen mode

It is best to do the following. It is also really nice on the eyes.

const value_to_check: string = "purple";

if (["green", "blue", "red"].includes(value_to_check)) {
    // do the thing
}

Enter fullscreen mode Exit fullscreen mode

Thanks for coming to my ted talk! - German

Top comments (0)