14 ms·
The match statement is nice, but in JS it's easy enough to just index a map. {'abc': 2, 'def': 3}[x] ?? 'default';
by jimmaswell 5y ago
The match statement is nice, but in JS it's easy enough to just index a map.
{'abc': 2, 'def': 3}[x] ?? 'default';
- unfocussed_mike 5y agoEasy to write. Less easy to read.
- fermentation 5y agoPlus you have to actually allocate and evaluate the whole map right? Like if the values are FromASlowComputation() you'd have to do something else.
- francislavoie 5y agoYou can do the same in PHP, but again, not as nice to read: ['abc' => 2, 'def' => 3][$x] ?? 'default';
- idoubtit 5y agoThe example in the article is poorly chosen, because an associative array (map) would be more suitable. What you wrote is almost the same with PHP: ['abc' => 2, 'def' => 3][$x] ?? 'default'; PHP's `match` is a kind of functional `switch`. For instance, in the following example, an associative array would induce several useless function calls, and `match` is more readable than a sequence of if+returns: return match ($key) { "id", "ID" => unique_id(), "UUID" => generate_uuid(), default => findExternalId($key), };