Is there a good JS shorthand reference out there?
Asked Answered
L

5

31

I'd like to incorporate whatever shorthand techniques there are in my regular coding habits and also be able to read them when I see them in compacted code.

Anybody know of a reference page or documentation that outlines techniques?

Edit: I had previously mentioned minifiers and it is now clear to me that minifying and efficient JS-typing techniques are two almost-totally-separate concepts.

Lode answered 10/10, 2010 at 7:59 Comment(0)
K
44

Updated with ECMAScript 2015 (ES6) goodies. See at the bottom.

The most common conditional shorthands are:

a = a || b     // if a is falsy use b as default
a || (a = b)   // another version of assigning a default value
a = b ? c : d  // if b then c else d
a != null      // same as: (a !== null && a !== undefined) , but `a` has to be defined

Object literal notation for creating Objects and Arrays:

obj = {
   prop1: 5,
   prop2: function () { ... },
   ...
}
arr = [1, 2, 3, "four", ...]

a = {}     // instead of new Object()
b = []     // instead of new Array()
c = /.../  // instead of new RegExp()

Built in types (numbers, strings, dates, booleans)

// Increment/Decrement/Multiply/Divide
a += 5  // same as: a = a + 5
a++     // same as: a = a + 1

// Number and Date
a = 15e4        // 150000
a = ~~b         // Math.floor(b) if b is always positive
a = b**3        // b * b * b
a = +new Date   // new Date().getTime()
a = Date.now()  // modern, preferred shorthand 

// toString, toNumber, toBoolean
a = +"5"        // a will be the number five (toNumber)
a = "" + 5 + 6  // "56" (toString)
a = !!"exists"  // true (toBoolean)

Variable declaration:

var a, b, c // instead of var a; var b; var c;

String's character at index:

"some text"[1] // instead of "some text".charAt(1);

ECMAScript 2015 (ES6) standard shorthands

These are relatively new additions so don't expect wide support among browsers. They may be supported by modern environments (e.g.: newer node.js) or through transpilers. The "old" versions will continue to work of course.

Arrow functions

a.map(s => s.length)                    // new
a.map(function(s) { return s.length })  // old

Rest parameters

// new 
function(a, b, ...args) {
  // ... use args as an array
}

// old
function f(a, b){
  var args = Array.prototype.slice.call(arguments, f.length)
  // ... use args as an array
}

Default parameter values

function f(a, opts={}) { ... }                   // new
function f(a, opts) { opts = opts || {}; ... }   // old

Destructuring

var bag = [1, 2, 3]
var [a, b, c] = bag                     // new  
var a = bag[0], b = bag[1], c = bag[2]  // old  

Method definition inside object literals

// new                  |        // old
var obj = {             |        var obj = {
    method() { ... }    |            method: function() { ... }
};                      |        };

Computed property names inside object literals

// new                               |      // old
var obj = {                          |      var obj = { 
    key1: 1,                         |          key1: 5  
    ['key' + 2]() { return 42 }      |      };
};                                   |      obj['key' + 2] = function () { return 42 } 

Bonus: new methods on built-in objects

// convert from array-like to real array
Array.from(document.querySelectorAll('*'))                   // new
Array.prototype.slice.call(document.querySelectorAll('*'))   // old

'crazy'.includes('az')         // new
'crazy'.indexOf('az') != -1    // old

'crazy'.startsWith('cr')       // new (there's also endsWith)
'crazy'.indexOf('az') == 0     // old

'*'.repeat(n)                  // new
Array(n+1).join('*')           // old 

Bonus 2: arrow functions also make self = this capturing unnecessary

// new (notice the arrow)
function Timer(){
    this.state = 0;
    setInterval(() => this.state++, 1000); // `this` properly refers to our timer
}

// old
function Timer() {
    var self = this; // needed to save a reference to capture `this`
    self.state = 0;
    setInterval(function () { self.state++ }, 1000); // used captured value in functions
}

Final note about types

Be careful using implicit & hidden type casting and rounding as it can lead to less readable code and some of them aren't welcome by modern Javascript style guides. But even those more obscure ones are helpful to understand other people's code, reading minimized code.

Kibitka answered 10/10, 2010 at 8:28 Comment(4)
x && (doWhentrue); << conditional. performance wise same as if(x) do;Aeromechanic
So after all this shorthand Math.pow(x, 2) is still the shortest way to square x?Ingesta
x*x is the shortest way currently :) Exponentiation operator is being implemented by modern browsers though (ES7): github.com/rwaldron/exponentiation-operator So you'll able to do x ** 2, more useful for other exponents of course.Kibitka
take heed! the use of arrow functions comes with the caveat that this will not be available within them. function () {} is not the same as () => {}Marivelmariya
P
17

If by JavaScript you also include versions newer than version 1.5, then you could also see the following:


Expression closures:

JavaScript 1.7 and older:

var square = function(x) { return x * x; }

JavaScript 1.8 added a shorthand Lambda notation for writing simple functions with expression closures:

var square = function(x) x * x;

reduce() method:

JavaScript 1.8 also introduces the reduce() method to Arrays:

var total = [0, 1, 2, 3].reduce(function(a, b){ return a + b; });  
// total == 6 

Destructuring assignment:

In JavaScript 1.7, you can use the destructuring assignment, for example, to swap values avoiding temporary variables:

var a = 1;  
var b = 3;  

[a, b] = [b, a]; 

Array Comprehensions and the filter() method:

Array Comprehensions were introduced in JavaScript 1.7 which can reduce the following code:

var numbers = [1, 2, 3, 21, 22, 30];  
var evens = [];

for (var i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evens.push(numbers[i]);
  }
}

To something like this:

var numbers = [1, 2, 3, 21, 22, 30];
var evens = [i for each(i in numbers) if (i % 2 === 0)];

Or using the filter() method in Arrays which was introduced in JavaScript 1.6:

var numbers = [1, 2, 3, 21, 22, 30];
var evens = numbers.filter(function(i) { return i % 2 === 0; });  
Polymerize answered 10/10, 2010 at 8:41 Comment(9)
i don't think any minifier would do any of this... :)Kibitka
@galambalazs: No, I don't think so as well. It would be incorrect for the minifier to do that, because such conversions would make code incompatible in engines that support versions 1.5 of JavaScript... Nevertheless, these are still a few options to shorten code in later versions, probably more for readability purposes rather than for minification.Polymerize
@galambalazs: I didn't interpret the question that way :) ... The OP asks: "I'd like to incorporate whatever shorthand techniques there are in my regular coding habits..."Polymerize
+1 Array comprehensions in JS 1.7? How did I not know about this?!Pinzler
"...and also be able to read them when I seem them in compacted code." :)Kibitka
@galambalazs: I interpreted that "and" as a logical OR :)Polymerize
@galambalazs: They might not be helpful in browser scripting (at the moment), but for example Spider Monkey supports JavaScript version 1.8 and Rhino version 1.7.Polymerize
SyntaxError: Unexpected token for this is what i get when i run code for each bla bla...Aeromechanic
Array comprehensions are no longer valid or supported. See Are ES6 Array Comprehensions No Longer Valid? and Array Comprehensions (MDN). Use filter() instead for situations like the example.Antoneantonella
H
3

You're looking for idioms of the JavaScript language.

It's certainly interesting to peek at what's new in JavaScript 1.6+ but you're not going to be able to use the language features (e.g., list comprehensions or the yield keyword) in the wild due to lack of mainstream support. It is worthwhile to learn about new standard library functions if you haven't had exposure to Lisp or Scheme, however. Many typical pieces of functional programming such as map, reduce, and filter are good to know and often show up in JavaScript libraries like jQuery; another useful function is bind (proxy in jQuery, to an extent), which is helpful when specifying methods as callbacks.

Hainan answered 10/10, 2010 at 8:49 Comment(0)
H
1

Getting the last value of an array

This is not really a shorthand, but more like a shorter alternative technique to the technique most people use

When I need to get the last value of an array, I usually use the following technique:

var str = 'Example string you actually only need the last word of FooBar';
var lastWord = str.split(' ').slice(-1)[0];

The part of .slice(-1)[0] being the shorthand technique. This is shorter compared to the method I've seen almost everyone else use:

var str = 'Example string you actually only need the last word of FooBar';
var lastWord = str.split(' ');
    lastWord = lastWord[lastWord.length-1];

Testing this shorthand's relative computing speed

To test this, I did the following:

var str = 'Example string you actually only need the last word of FooBar';
var start = +new Date();
for (var i=0;i<1000000;i++) {var x=str.split(' ').slice(-1)[0];}
console.log('The first script took',+new Date() - start,'milliseconds');

And then seperately (to prevent possible synchronous running):

var start2 = +new Date();
for (var j=0;j<1000000;j++) {var x=str.split(' ');x=x[x.length-1];}
console.log('The second script took',+new Date() - start,'milliseconds');

The results:

The first script took 2231 milliseconds
The second script took 8565 milliseconds

Conclusion: No disadvantages in using this shorthand.

Debugging shorthands

Most browsers do support hidden global variables for every element with an id. So, if I need to debug something, I usually just add a simple id to the element and then use my console to access it via the global variable. You can check this one yourself: Just open your console right here, type footer and press enter. It will most likely return the <div id="footer> unless you've got that rare browser that doesn't have this (I haven't found any).

If the global variable is already taken up by some other variable I usually use the horrible document.all['idName'] or document.all.idName. I am of course aware this is terribly outdated, and I don't use it in any of my actual scripts, but I do use it when I don't really want to type out the full document.getElementById('idName') since most browsers support it anyway, Yes I am indeed quite lazy.

Hypo answered 28/12, 2013 at 22:56 Comment(0)
C
1

This github repo is dedicated to byte-saving techniques for Javascript. I find it quite handy!

https://github.com/jed/140bytes/wiki/Byte-saving-techniques

Collectivity answered 4/1, 2016 at 20:20 Comment(1)
You made my day ! This gist is nice to read, I've just learnt a lot of things ;)Southwest

© 2022 - 2024 — McMap. All rights reserved.