this post was submitted on 20 Feb 2025
2 points (100.0% liked)

General Discussion

0 readers
2 users here now

A place to talk about whatever you want


This is a forum category containing topical discussion. You can start new discussions by mentioning this category.

founded 2 months ago
 

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:

top 3 comments
sorted by: hot top controversial new old
[–] inaction_figure@fosstodon.org 1 points 4 weeks ago

@julian

Some really dislike switch. It's ok to like and use switch for its intended purpose, as long as you understand its idiosyncrasies.

Thanks for sharing this!

[–] nextgraph@fosstodon.org 1 points 4 weeks ago (1 children)

@julian so adding a && true at the end of your condition, should work, right?

case object && object.foo && true: {  
[–] julian@community.nodebb.org 1 points 4 weeks ago

@nextgraph@fosstodon.org in my case, I just casted it as bool: !!object.foo. You could also object.hasOwnProperty('foo'), although that would be true if object.foo = null too :joy: