DEV Community

Discussion on: A neat little trick with JavaScript's indexOf()

Collapse
 
alainvanhout profile image
Alain Van Hout • Edited

It's a neat trick, but 'saving a few characters' is a notoriously bad reason to do something a certain way (unless saving a few characters is the prime motivator in your specific use-case). That's because there is a big difference between 'concise' and 'dense'. The former is somewhat preferable, all things being equal. The latter is to be avoided at all cost (again, unless your specific use-case demands it).

Beyond that, to a degree this is similar to using the following approach to declare a default value:

const foo = bar || 'my default value';

That serves as a clean way to do that if it's a convention that your team has decided upon.

Collapse
 
werninator profile image
Patrick Werner

I mean, if you strike it as bad, it's your convention or set of rules. I can see where you're coming from though and probably many people think so too. Both the bitwise NOT operator for indexOf and your code snippet are based on relying on the truthfulness of an expression.

But I think it's one of JavaScript's most interesting feats that it can work like that. That's the reason I wrote this, because I think it's interesting that this works at all.

Collapse
 
alainvanhout profile image
Alain Van Hout

It's indeed interesting, no doubt about that :).

It reminds me a bit of the following line of JavaScript, that was making the round a couple of years ago, and which manages to showcase a lot of neat JS with very little code: (source)

[].forEach.call($$("*"),function(a){
  a.style.outline="1px solid #"+(~~(Math.random()*(1<<24))).toString(16)
})

Back to the original topic, I wrote my response from the perspective of 'should this be used?', which isn't so much a matter of interestingness as it is one of maintainability. That's not the same as saying it's 'bad', but in any setting where you're not the only contributing developer, code generally has to do better than simply not being bad.

(of course I'm ignoring the already mentioned String.prototype.includes() in all this)