1
switch(true) gotcha (community.nodebb.org)
submitted 5 days ago* (last edited 5 days ago) by julian@community.nodebb.org to c/general-discussion@community.nodebb.org

I discovered this week a little footgun if you happen to use this bit of syntactic sugar:

const object = {
    foo: 'bar',
}

switch (true) {
    case object && object.foo: {
        // This will never execute
    }

    default:
        // ...
}

The cases in your switch(true) must actually return true, not truthy, for the case to execute.

Using switch(true) is a bit of a controversial coding practice, since it's only meant to replace long if..else if..else chains. Literally has no additional utility except aesthetics... but I like it nevertheless :joy_cat:

no comments (yet)
sorted by: hot top controversial new old
there doesn't seem to be anything here
this post was submitted on 20 Feb 2025
1 points (100.0% liked)

General Discussion

0 readers
4 users here now

A place to talk about whatever you want

founded 1 month ago