this post was submitted on 19 Jun 2025
5 points (100.0% liked)

JavaScript

2409 readers
9 users here now

founded 2 years ago
MODERATORS
top 3 comments
sorted by: hot top controversial new old
[–] [email protected] 1 points 4 hours ago

Interesting and valid point, but Kotlin's when is not actually pattern-matching. It really is just syntactic sugar for if-else, like you've demonstrated.
Actual pattern-matching allows matching on the structure of a data type. So, you formulate a pattern to describe the structure and then you can choose different code paths based on whether the pattern matches or you can also access fields inside of this data type.

Rust allows pattern-matching even in variable assignments, which is going to look funky, but I think it shows quite well that pattern-matching isn't just a fancy switch statement: https://play.rust-lang.org/?version=stable&mode=debug&edition=2024&gist=3a8d126fa0cb9736597793915b00dd5d

So what happens is that:

  • there's a check whether the data type has the described structure, and
  • where the pattern contains wildcards (like variable 'slots'), the corresponding field values from the data type get put into those wildcards.

When someone writes this in Rust:

let x = 1;

It's still pattern matching under the hood, but the pattern x is just a singular wildcard, so the right-hand side just gets 'assigned' to that variable name.

And with these simple examples, you might think that being able to access field values this way is silly, since you can also access them via my_data_type.foo, but it becomes more useful with deeply nested data types, and in particular in statically typed languages, it allows you to work with different data types without type casting. So, it would be more useful of a feature for TypeScript than it might be for JavaScript.

[–] chickenf622 5 points 8 hours ago (1 children)

This is probably just my general dislike of chained ternary operators, but why not just write this out the "long" way to make intention clearer?

[–] [email protected] 1 points 22 minutes ago

Yeh, I'd just do early return.
It's not much more typing, and I find it easier to read and navigate specific conditional paths.

Some built in pattern matching would be cool (like the when keyword), but I'm not going to force it into my code