Discuss Some JS Style Guide


This will discuss some of JS style guide proposal made for my project:

Use ES6 features effectively

We write ES6 so we should get the best out of it. For a quick recap of ES6 features, check this http://es6-features.org/

Here are some quick rules to follow

  • Do not use ; In ES6 we don't have to use ; at the end of a statement
  • User const for variable that doesn't change, let for variable that will be mutated. Avoid var.
  • Use string interpolation instead of string concat ref
// bad
var bar = "baz"
var foobar = "foo" + bar

// good
const foobar = `foo${bar}`
  • Use getters/setters ref

jQuery

Generai rules:

  • Always declare jQuery object a name starts with $

AJAX

  • Do not use .getJson() or .get(), always use $.ajax()
  • Use promise (deferred) instead of success, error, complete events
// promise examples
$.ajax({ ... }).then(successHandler, failureHandler);

// or
var jqxhr = $.ajax({ ... });
jqxhr.done(successHandler);
jqxhr.fail(failureHandler);

// or
$.ajax({
  url: url,
  type: "GET"
  data: {},
  dataType: "JSON"
})
.done((data, textStatus, jqXHR) => {
  // success callbacks
})
.fail((jqXHR, textStatus, errorThrown) => {
  // error callbacks
})
.always((data|jqXHR, textStatus, jqXHR|errorThrown) => {
  // complete callbacks
})

Lodash

Lodash (https://lodash.com/docs/) provides handful of methods that helps with collection/string manipulation and other ultilities.

A few frequetly used functions such as _.uniqueId to generate unique id (e.g. for new records), .remove to remove certain elements that match a predicate from an array, .difference to compare 2 collections.

React

Component structure

  • class definition
  • constructor
  • "component" lifecycle events (e.g. ComponentDidMount)
  • event handlers
  • getters
  • render
  • defaultProps
  • proptypes

Passing props

// single prop
<Product name="product name" />

// multiple props
<Product
  name="product name"
  price="$123.45"
  discount={false}
/>

Avoid jQuery in React

DOM manipulation should be handle by React, not jQuery

Exceptions:

  • AJAX request handling
  • Bootstrap elements that use jQuery (e.g. Bootstrap modal)

Always declare propTypes for Component This will allow React to check and warning about missing/invalid props. Also make the component more readable.

ComponentName.propTypes = {
  email:      React.PropTypes.string,
  seats:      React.PropTypes.number,
  settings:   React.PropTypes.object,
  callback:   React.PropTypes.func,
  isClosed:   React.PropTypes.bool,
  any:        React.PropTypes.any,
}

Always add <tbody> for table If you don"t insert <tbody> for table, browsers will inject it into table while React may continue to add new <tr> tags that fall outside of <tbody>

Use Flux/Redux to control component state avoid maintaining state internally in component.

i18n: order keys by alphabet

filename should be same as component name for better reference from other files.