Skip to content

conveyal/javascript

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

31 Commits
 
 
 
 

Repository files navigation

JavaScript

Tools & best practices for writing JavaScript across Conveyal projects.

Completely necessary for modern JavaScript development. Install with a package manager. YOU MUST use a 6.x.x version for Conveyal development.

$ brew install node@10

Use yarn as an npm replacement to manage dependencies.

$ brew install yarn

Use n to manage Node.js versions.

$ yarn global add n
$ n latest

Certain conventions should be followed due to the new functionality that ES6 brings. Highlights:

  • When working on a new codebase, use let for variables that will change their value over time, and const for variables which cannot be reassigned.
  • Use Arrow Functions (=>) in place of function expressions when possible.
  • Use Promises instead of the function asyncFunc (input, function callback (err, result) {}) {} style.

Other Tips

Promiseified functions can be awaited allowing for this style of functions:

async function chainAnimationsAsync(elem, animations) {
  let ret = null
  try {
    for(const anim of animations) {
      ret = await anim(elem)
    }
  } catch (e) {
    /* report and keep going */
  }
  return ret
}

Always use debug instead of console.log

Debug is a tiny library that allows you to selectively turn on and off namespaced log statements in the browser and in node.

import dbg from 'debug'
const debug = dbg('library:module')
debug('log this!')

The log will only be shown in the browser when you turn it on via simple regexp in the console:

> localStorage.setItem('debug', 'library*')

Don't use bind

Do:

onClick={(e) => this.handleEvent(e)}

Don't

onClick={this.handleEvent.bind(this)}

In classes you can auto-bind to the instance by using class properties and arrow functions.

class Foo {
  handleEvent = (e) => {
    // inside this function `this` will always be the instance of `Foo`
  }
}

Don't use jQuery

To start, see: http://youmightnotneedjquery.com/. Use ES6 and smaller modern JavaScript libraries instead of using jQuery.

Use fetch instead of $.ajax/$.get/$.post:

fetch(url)
  .then(res => res.json())
  .then(data => {
    console.log(data)
  })

About

Tools & best practices for writing JavaScript across Conveyal projects

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 2

  •  
  •