4 posts tagged

JavaScript

Jafar Husain on async/await

Ilya Gelman

With latest browsers and NodeJS support, features like async/await are becoming the norm in modern web-development. For new developers, especially for those who’s JavaScript is their first language, it is very important to deeply understand how such features work to make the most out of them.

In his talk from JSConf US 2015, Jafar Husain explains async programming features in newest versions of JavaScript including promises, generators, and async functions.

On Thursdays we post videos that we believe are worth watching and that can make you a better front-end developer. Have such a video to share? Share with us

Async/Await   JavaScript   Video

Lea Verou on Regular Expressions

Ilya Gelman

Regular expressions are a very powerful thing and a lot of junior developers struggle to wrap their heads around it and remember the syntax.

In her talk from Fluent Conference 2012, Lea Verou explains Regular Expressions in JavaScript in a very interactive and interesting way.

There is a library called Verbal Expressions that allows you to describe regular expressions in an expressive way (no pun intended). There are implementations in various languages, in JavaScript it looks something like this:

VerEx()
    .startOfLine()
    .then('http')
    .maybe('s')
    .then('://')
    .maybe('www.')
    .anythingBut(' ')
    .endOfLine();

The above code will compile into this RegExp:

/^(http)(s)?(\:\/\/)(www\.)?([^\ ]*)$/

On Thursdays we post videos that we believe are worth watching and that can make you a better front-end developer. Have such a video to share? Share with us

P.S. Remember, never try to parse html with regular expressions!

JavaScript   Regular Expressions   Video

Approaches to Immutability

Adam Klein

Immutability is a concept that’s easy to fall in love with, but it’s not always easy and straightforward to exercise. Here we will explore a set of tools and strategies that make the task easier.

Plain JavaScript

Using plain JavaScript requires no external library and no extra knowledge, but it requires way too much boilerplate. For example, setting a nested property in the state:

{
  ...state,
  parent: {
    ...(state.parent || {}),
    key: 'newValue'
  }
};

Too much boilerplate for such a simple and common task.

ImmutableJS / seamless-immutable

Both ImmutableJS and seamless-immutable are libraries that wrap plain objects with classes that enforce Immutability. Which means you simply cannot mutate the objects, even by mistake.

Example using ImmutableJS:

import { fromJS } from 'immutable';

const state = fromJS({ }) // Must wrap the object with Immutable
state.parent.key = 'newValue'; // => Throws error

return state.setIn('parent.key', 'newValue'); // Returns a new object

The API gives you a decent set of tools for changing and accessing the object.

Because you are not working with plain objects, integration with 3rd-party tools might require special attention, e. g.: when you use redux devtools to import or export the state, redux-persist to save and restore parts of it, when you use combineReducers, and basically every 3rd-party tool that serializes and deserializes the state, or uses methods that work on plain objects but not on Immutables.

This can be quite annoying, and you may find yourself battling with the tool instead of celebrating it.

Bottom line: if you are willing to sacrifice the disadvantages for the sake of enforcing immutability – choose one of these libraries.

lodash/fp

This is the functional-programming version of the famous lodash library. Each lodash method has an equivalent lodash/fp method, just with the object passed as the last parameter instead of first:

// lodash
_.set(obj, key, value);

// lodash/fp
_.set(key, value, obj);

Changing a nested property with lodash/fp:

import { set } from 'lodash/fp';

set('parent.key', 'value', state);

Updating a property based on its current value:

import { update } from 'lodash/fp';

update('parent.key', (value) => value + 1, state);

Functions are automatically curried, which means these calls are equivalent:

import { set } from 'lodash/fp';

set(key, value, obj);
set(key, value)(obj);

This also means you can chain operations like this:

import { flow, set, update } from 'lodash/fp';

flow([
  update('parent.key', (value) => value + 1),
  set('parent.key', 'value')
])(state);

Bottom line: if you are willing to sacrifice enforcing immutability for a very rich API, higher performance and need easy integration with 3rd-party libraries this is a very good solution.

The functional style can be odd in the beginning, but very rewarding after you get used to it.

Comparison Table

  ImmutableJS lodash/fp
Performance Lower Higher
API Decent Very rich
Immutability Enforced Not enforced (error prone)
3rd-party integration More difficult Effortless
Immutability   JavaScript

On CoffeeScript and ES6

Ilya Gelman

The ECMAScript 6 specification is approaching its approval, and with it are a number of great features. Should we stop writing CoffeeScript altogether and start using the upcoming ES6?

It appears that it is still too early to put CoffeeScript in its grave. There is still something that makes CoffeeScript more attractive than vanilla JS for everyday use: its syntax.

Many great features of CoffeeScript have already been implemented in ES6, but CoffeeScript remains full of those little things that make everyday jobs easier:

  • You don’t have to think about hoisting, vars, lets or returns.
  • Syntactic sugar such as not or unless keywords or one line conditionals
  • Code is cleaner without function, {}, and ;

There are some more awesome features.

Splat arguments:

race = (winner, runners...) -> print winner, runners

Existential operator:

alert "I knew it!" if elvis?

Conditional assignments:

date = if friday then sue else Jill

Chained comparisons:

healthy = 200 > cholesterol > 60

Even with all these great features, many reasons to stick with plain JavaScript over CoffeeScript have been made. Let’s take a look at them:

Curly braces are fine

Most JS programmers don’t understand what Coffee programmers have against curly braces or semicolons. The C-like syntax is just fine. How can a couple of extra characters be an argument against language quality?

In practice, less characters means less code, which could result in less bugs. It’s easier to catch errors when you have less visual noise. Navigating a file is easier with 20 lines of code rather than 50. Also CoffeeScript won’t let you write un-indented code, no matter how lazy you are.

Of course, it is mostly a matter of choice. Subjectively, I enjoy my code when it’s more human readable. Some may believe that expressiveness and aesthetics of code, especially with syntactic sugar libraries like SugarJS, are not really rational arguments in a JavaScript vs. CoffeeScript discussion.

CoffeeScript is harder to understand than plain JS

It is largely a matter of habit. CoffeeScript does take some learning, but so will the new EcmaScript 6 syntax. It is sometimes hard to see the benefits of it before you start using it for real.

One of the arguments against CoffeeScript syntax was that it is too obscure for JS programmers and only understandable by people with backgrounds in languages such as Ruby. Now, as some of the CS syntax is part of the future of JS itself, I believe that this argument has been put to rest.

It doesn’t support ES6 features

Yet. There is no logical reason to believe that good ES6 features won’t be also implemented in CS once they become widely supported. Until then, there is no reason to make a language that compiles into another compiled language.

You need a pre-compiler

One of the strongest argument against CoffeeScript is that you will need a compiler for it forever, while the need for the ES6 compiler will be eventually eliminated.

If you use SCSS or Autoprefixer with Grunt or, even better, Gulp, to handle compilation (and you probably should) then using CoffeeScript is as simple as writing a few lines of code and you are ready to go. And with sourcemaps, you can also debug it easily in browser.

By the way, if you look at the ES6 Compatibility Table, you will see that there are still too many red cells to say that you won’t need a compiler in the near future. It may take months if not years before all browsers will support all features of the next ECMAScript spec.

Most of the world uses JavaScript

This is just as true as the fact that most of the world also uses PHP and .net. But the lower entry level of Javascript also comes with the price of too many inexperienced programmers who write thousands of lines of bad code and then release them as unusable, buggy bower components.

The truth is, there are people out there using CoffeeScript to write awesome products like Atom, Discourse, Github, Dropbox, Hubot, Pow, or Koding IDE.

The bottom line

Both sides of this discussion have reasonable arguments, and choosing between CoffeeScript and plain JS still remains a matter of opinionated choice. Personally, as a Ruby programmer, I would be happy to write Ruby, be it Opal for web development or mruby for Arduino. But we live in a world where JavaScript has taken the leadership.

You will have to know JavaScript anyway. At the end, it’s just what CoffeeScript is. But CS can save you a lot of nerves and time. If you already use Coffee, the bottom line is don’t rush to rewrite everything with the cutting-edge ES6. The odds are that future versions will support ES6 features. And if you don’t yet code in CoffeeScript, learning it may not be a bad idea.

CoffeeScript   JavaScript