10

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?

Dave Land
  • 2,257
  • 1
  • 18
  • 21
mkoryak
  • 57,086
  • 61
  • 201
  • 257
  • The only shortcuts that I would actually use are `!!` and `+"1"`. The rest have unintended side effects (`~~10000000000000 == 1316134912`, for example) or just look funny. – Blender Aug 04 '13 at 02:15
  • @mkoryak: I was talking more about the bitwise operations, which will convert your numbers to signed 32-bit integers. – Blender Aug 04 '13 at 02:18
  • @mkoryak, aside from being "too broad", you should use the "Answer Your Own Question" checkbox, or move the answer part to an answer. – Brigand Aug 04 '13 at 02:20
  • its not too broad, unless you know of any more of these that i dont know about. I cant answer my own question because I think there are more of these that I don't know about, and people dont tend to answer questions that have an accepted answer, no? – mkoryak Aug 04 '13 at 02:20
  • 1
    More of what, exactly? *Shortcut* is an incredibly vague term and you could give pretty much any answer as a shortcut for something else. – Dennis Aug 04 '13 at 02:24
  • ok, help my come with with a better title. i have examples of what i am looking for right there in the question. More of those! – mkoryak Aug 04 '13 at 02:25
  • 'Idiom' might be a better word than 'shortcut'... it's often used to bowdlerize shitty coding practices in C and Perl :P – Dancrumb Aug 04 '13 at 02:33
  • Idioms are generally good, shortcuts are generally bad. Programmers like idioms, bosses like shortcuts (who cares how the code looks, anyway? Clients don't see it!) – Brigand Aug 04 '13 at 02:36
  • @mkoryak it is too broad. Read the source of [lodash](http://lodash.com/) for a zillion more. – djechlin Aug 04 '13 at 02:38
  • [See my question here](http://stackoverflow.com/questions/17433873/pattern-for-treating-zero-as-truthy) (which I will note had mixed reactions) for a far more specific question regarding Javascript "shortcuts" that *still* had several answers. Your question is *far* broader. – djechlin Aug 04 '13 at 02:40
  • 2
    `~~2.333` This's new to me, thanks! – Derek 朕會功夫 Aug 04 '13 at 02:56
  • 1
    As a 14k rep user, you should *really* know by now that this question is totally off-topic for Stack Overflow. – user229044 Aug 04 '13 at 03:40

3 Answers3

15

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.

Dancrumb
  • 26,597
  • 10
  • 74
  • 130
4
  • 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.

Blender
  • 289,723
  • 53
  • 439
  • 496
  • 1
    `n | 0` is the same as `Math.trunc` for the signed 32-bit integer range. It is not the same as `Math.floor` for negative values. – polytypic Aug 31 '20 at 10:07
3

I see this one a lot:

myString = "Some string."
b = myString[myString.length - 1]; // get the period

Should be

b = myString.slice(-1);

The for while loop.

for (var i=0; i < a.length; i++) {
    var x = a[i];
    console.log(x);
}

to

for (var i=0,x; (x=a[i++]) != null; ) {
    console.log(x);
}

Put this at the top of a script.

String.prototype.has = Array.prototype.has = function(a){ return this.indexOf(a) !== -1; }

Turns these

if (myString.indexOf(a) !== -1)
if (myArray.indexOf(a) !== -1)

to these

if (myString.has(a))
if (myArray.has(a))

For when you need to put 42 in your code, but sneakily.

var answer = ((((1<<2)|1)<<2)|1)<<1;

CoffeeScript

... need I say more?

Brigand
  • 84,529
  • 20
  • 165
  • 173
  • Thanks, this is useful and very much on the topic of what i was asking for. Yes coffeescript rocks :) – mkoryak Aug 04 '13 at 02:37
  • Yeah, the question just reminded me of a lot of "So, which is your favorite" questions at first, and second glances :-) – Brigand Aug 04 '13 at 02:39
  • This `for (var i=0,x; (x=a[i++]) != null; )` is brilliant. Thanks! – user3557327 Mar 03 '15 at 17:01
  • As with many shortcuts, that array one fails in unexpected ways. For `a=[1,2,,3,4,5]`, you only get the 1 and the 2. This is because `undefined == null` is `true`. – Dancrumb Nov 01 '16 at 17:21