Guides for programing JavaScript in style
- Use ESLint.
- Always use ES6.
- Leave one space between
ifand(.
if (something) {
//some work here;
}- Prefer this form for multiline
ifstatements.
if (something) {
// do stuff
// even more stuff
} else {
// some other stuff
// real stuff
}- Don't include spaces between
(and function declaration.
function bar() {
return foo;
}
var bar = function() {
return foo;
}- Initialize arrays with
[].
var array = [];- Initialize objects with
{}.
var object = {};- Leave one space after
{and before}when initializing objects on the same line.
var map = { ready: 9, when: 4, "you are": 15 };- Prefer single line object/array initialization.
var object = { when: 4, ready: 9, "you are": 15 };
var array = [1, 2, 3];- Prefer this form for constructors.
function Foo(bar) {
this.bar = bar;
}
Foo.prototype.getBar = function() {
return this.bar;
};
var foo = new Foo("bar");- When chaining methods indent one time.
var elements = [$('.button'), $('.navbar')];
elements
.addClass("foo")
.children()
.html()
.end()
.appendTo("body");- Whenever possible make callbacks named functions, it makes the stack trace easier to understand.
function callback(error, result) {
//some work here
}
bar(foo, callback);- Always use
===. - You can use
==when checking for both null and undefined.
undefinedOrNull == null;- When evaluating that an array or string is not empty, evaluate truthiness.
if (array.length) {
// array is not empty
} else {
// array is empty
}
if (string) {
// string is not empty
} else {
// string is empty
}- When evaluating that a reference is true, evaluate its truthiness.
if (foo) {
// foo is true
}- When evaluating that a reference is false, use negation to coerce a true evaluation.
if (!foo) {
// foo is false
}