I'm looking for clever or silly JavaScript code snippets that might take a moment to grasp, despite being simple at their core. For instance, check out this one:
```javascript
const f = n => [false, true][n % 2];
```
Can anyone share similar examples? I'm open to snippets of varying lengths, but I'd prefer single-line functions for easy reading.
5 Answers
Check out this simple snippet for generating a random hex color:
```javascript
'#'+(Math.random()*(1<<24)|0).toString(16);
```
This gives you a random hex code, but just be aware that it might not always return valid six-character hex values!
Nice, I’ll definitely use that!
Here's a fun one that plays with naming object properties randomly:
```javascript
const obj = { [Math.random().toString(36).slice(2)]: "Foo" };
```
And if you need an object with "Infinity" as a key, you can use this:
```javascript
const obj = { [1 / 0]: "possibilities" };
```
What's the deal with "keeping the size of your code down"? I thought you could only have one `Infinity` key per object.
Here's a simple pattern for a `while` loop that I like:
```javascript
let i = -1;
while(++i < length) { }
```
And if you're working with functions producing multiple expected outcomes, you can do:
```javascript
let out;
while((out = someResult(5, 99, 3)) != null) {
// operate on the updated variable
}
```
For anyone needing to convert Roman numerals to Arabic numerals in the shortest way possible, check this out:
```javascript
rom2int=r=>[...r,s=l=0].map(i=>(j={I:1,V:5,X:10,L:50,C:100,D:500,M:1000}[i],s+=(l<j?-l:l),l=j))&&s;
```
Did you come up with this yourself, or is it a popular solution?
Though it's impressive, it feels like it does too much for my taste. It's a bit hard to follow!
When you're sorting with `.sort()` or `.toSorted()`, use `a` and `z` as parameter names. It avoids confusion about the sort direction:
```javascript
scores.toSorted((a, z) => a - z); // a to z, low to high
scores.toSorted((a, z) => z - a); // z to a, high to low
```
Edit: Just realized I misread one section, but it’s still a cool trick that can help clarify what's happening! Another fun one:
```javascript
const f = n => !(n & 1);
```
With 25 years in the game, I’ll definitely use this trick going forward! Well done!
You might want to improve it to:
```javascript
'#'+(Math.random()*(1<<24)|0).toString(16).padStart(6, "0"); ``` This ensures you always get valid hex values.