Skip to content

Instantly share code, notes, and snippets.

@akshaye
Last active December 11, 2015 12:59
Show Gist options
  • Select an option

  • Save akshaye/4604717 to your computer and use it in GitHub Desktop.

Select an option

Save akshaye/4604717 to your computer and use it in GitHub Desktop.
Things i learned while reading Async JavaScript

##Elegant

In Javascript, following code

function(x) { return foo(x); }

is equivalent to just writing foo.

So, following code

foo(function(x) { return bar(x); });

is just an unneccesarily verbose way of writing

foo(bar);

##Caution

This elegance can quickly make you write incorrect code, unless you properly understand basic JavaScript functions' behavior.

["1", "2"].map(function(x) { return parseInt(x);});

may be simplified to much cleaner code

["1", "2"].map(parseInt);

But you'll not get the result that you were expecting.

Part 2

For example, following code

someArray.map(function(x){
  return foo(x.value);
});

can be understood as

someArray
.map(function(x){
  return x.value;
})
.map(function(value){
  return foo(value);
})

which can then be simplified as

someArray
.map(function(x){
  return x.value;
})
.map(foo)

We can further simplify the first part of the expression by refactoring following method:

function getValue(x) {
  return x.value;
}

Which leaves our original expression as simple and elegant

someArray
.map(getValue)
.map(foo)

###Functions that return functions

To make our getValue method more generic, we could write something like

function get(attr) {
return function(object) {
  return object[attr];
}}

leaving our original expression as

someArray
.map(get('value'))
.map(foo)

##Resources
Captain Obvious on JavaScript
A JavaScript Optional Argument Hazard
Async Javascript
Annotated EcmaScript
JavaScript Garden

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment