Share Your Favorite Clever or Silly JavaScript Code Snippets!

0
4
Asked By CuriousCoder93 On

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

Answered By HexWizard77 On

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!

ColorMaster11 -

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.

WowCat22 -

Nice, I’ll definitely use that!

Answered By CharmingCoder On

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" };
```

OptimizedCoder -

What's the deal with "keeping the size of your code down"? I thought you could only have one `Infinity` key per object.

Answered By LoopLover On

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
}
```

Answered By CreativeCoder99 On

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;
```

GolfKing78 -

Did you come up with this yourself, or is it a popular solution?

ScriptSavant15 -

Though it's impressive, it feels like it does too much for my taste. It's a bit hard to follow!

Answered By CodeSmith42 On

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);
```

JavaGuru28 -

With 25 years in the game, I’ll definitely use this trick going forward! Well done!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.