Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript idioms for doing common things [closed]

Tags:

javascript

I've been programming JS for a bunch of years and I am still finding new shortcuts for doing things. I am wondering if there are more that I do not know about.

Here are the shortcuts I know about:

edit: I agree that you should generally never do this stuff, and that there could be a better way to describe it as to be less broad, but the best I can do is describe it by example.


Instead of this

if("foobar".indexOf("foo") > -1) 

Do this

if(~"foobar".indexOf("foo"))

Instead of this

var foo = Math.floor(2.333)

Do this

var foo = ~~2.333

Instead of this

var foo = parseFloat("12.4")
var bar = parseInt("12", 10)

Do this (not huge fan of this one )

var foo = +"12.4"
var bar = +"12"

Instead of this

if(isNaN(foo)

Do this

if(foo != foo)

Instead of this

(function(){ ... })()

Do this

!function(){ ... }()

Convert anything to a boolean by prefixing it with !!

var isFoo = !!foo

There you have it, my list of things to never do to your coworkers.

Can anything else be added here?

like image 600
mkoryak Avatar asked Aug 04 '13 02:08

mkoryak


2 Answers

This question will probably get closed as being too broad, and this answer may garner its fair share of downvotes for not answering directly, but here goes.

Please, please, be really circumspect about using "shortcuts" in a programming language, because... really... who are they helping?

Most of these shortcuts sacrifice clarity and explicitness for keystrokes. You won't find a single, competent, professional coder who will agree that that is a sensible trade off.

Consider

if("foobar".indexOf("foo") > -1)

to

if(~"foobar".indexOf("foo"))

You've saved 4 characters... whoopie! However, you've also guaranteed that anybody who doesn't know this shortcut has a very slim chance of being able to figure out what is going on here... and certainly not with ease.

Reading the definition of indexOf is enough to understand the explicit version. For the second one, you need to understand what ~ means (which is a fairly uncommon operator in JS). You then need to know what the bitwise complement of -1 is. You then need to realise that it is truthy.

It's a foolish tradeoff and it is a hallmark of many of these idioms.

Please don't do it. This isn't the 80s.

like image 108
Dancrumb Avatar answered Oct 21 '22 02:10

Dancrumb


  • n | 0 floors n (only if n is within the signed 32-bit integer range). It's faster than Math.floor() in most browsers last I checked.
  • undefined == null, but neither are equal to false.
  • Instead of x == 'a' || x == 'b' || x == 'c', you can do ['a', 'b', 'c'].indexOf(x) !== -1

The only truly short shortcut that I've seen in production code is the unary + to convert strings into numbers.

like image 24
Blender Avatar answered Oct 21 '22 00:10

Blender