switch(true) gotcha
-
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 returntrue
, not truthy, for the case to execute.Using
switch(true)
us a bit of a controversial coding practice, since it's only meant to replace longif..else if..else
chains. Literally has no additional utility except aesthetics... but I like it nevertheless -
@julian so adding a `&& true` at the end of your condition, should work, right?
```
case object && object.foo && true: {
``` -
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!
-
@julian so adding a `&& true` at the end of your condition, should work, right?
```
case object && object.foo && true: {
```@nextgraph@fosstodon.org in my case, I just casted it as bool:
!!object.foo
. You could alsoobject.hasOwnProperty('foo')
, although that would be true ifobject.foo = null
too -
@julian not sure which language this is, but isn't there any sort of short-circuiting on `if`?
`if condition1 && condition2` should immediately stop if condition1 is false, leaving condition2 never evaluated
-
@julian not sure which language this is, but isn't there any sort of short-circuiting on `if`?
`if condition1 && condition2` should immediately stop if condition1 is false, leaving condition2 never evaluated
@trwnh@mastodon.social there is, and it'd work in this case. The issue is that as the condition is evaluated, if it doesn't resolve to boolean true, then the case won't execute.
In the example above it resolves (in JavaScript, anyway) to
"bar"