Idea: switch (value instanceof) { case MyClass: }

6 views
Skip to first unread message

Alex Vincent

unread,
Aug 11, 2023, 9:29:16 AM8/11/23
to SES Strategy
Just something that popped into my head yesterday.  In some prototype code I wrote, I had some long `if ((foo instanceof A) || (foo instanceof B) || ...) { /* do something */ }` which I've been building recently.  I later moved over to `switch (foo.kind) { case Kind.A: case Kind.B:, ... }`

New syntax of the form `switch (value instanceof) {  case A: /* do something */ }` might be more concise, and possibly something an engine could optimize a bit.  (I could see some manipulations of Symbol.hasInstance particularly when A and B inherit from C, but not D.)

This is _just_ an idea I haven't fully explored yet.  I'm not even sure it's a _good_ idea,  I'm just throwing it out here to see how people react.

Alex

--
"The first step in confirming there is a bug in someone else's work is confirming there are no bugs in your own."
-- Alexander J. Vincent, June 30, 2001

Mathieu Hofman

unread,
Aug 11, 2023, 9:51:55 AM8/11/23
to Alex Vincent, SES Strategy
Hi Alex,

I'm not sure if this has been explored before, but maybe ES Discourse has some related topics?

In this particular case, I don't think `switch` would be an appropriate place for this feature because it's possible for multiple matches to be positive for instanceof, but it's never possible for the current switch. The pattern matching proposal may make such custom switching easier to write. I don't believe it supports this particular use case built-in, but maybe one can write a `matchClass(Constructor)` helper to do so.

Mathieu

--
You received this message because you are subscribed to the Google Groups "SES-strategy" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ses-strategy...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/ses-strategy/CAEZ84427MDN9093h2KgamDVGyr%3Dvh7n7cRjH22VOppVnrHTt3A%40mail.gmail.com.

Jordan Harband

unread,
Aug 11, 2023, 11:40:21 AM8/11/23
to Mathieu Hofman, Alex Vincent, SES Strategy
Additionally, instanceof isn’t reliable with builtins (it’s forgeable and breakable) and doesn’t work cross-realm, so i wouldn’t want to encourage those semantics in the language further.

Reply all
Reply to author
Forward
0 new messages