Skip to content

Instantly share code, notes, and snippets.

@adamloving
Last active February 15, 2018 22:45
Show Gist options
  • Save adamloving/6075912 to your computer and use it in GitHub Desktop.
Save adamloving/6075912 to your computer and use it in GitHub Desktop.
Beautiful Javascript. This is an example of what I think good Javascript formatting looks like (my style guidelines). Fork this and show me how you like it, or comment if I forgot anything.
// camel case variable names (no underscores)
// instance variables are nouns
var myArray = [1, 2, 3]; // space after commas
// title case for class names (class names should be nouns)
// space before bracket
function Widget() {
// two spaces for indentation
var parameterOne = 1;
var parameterTwo = 2;
doSomething(parameterOne, parameterTwo);
}
// space before and after "="
// camel case key names, unless matching a server side format
// single quotes for strings
var myObject = {
myKey: 'value'
};
// space before and after parens
if (myArray.length === 0) {
var x = 1;
} else { // else uses one line
var y = 2;
}
// function names should be verbs
// space after params of function definition
logSomething = function(text) {
return console.log(text);
};
// when passing objects, use a space after the key, and after the comma
doSomething({ x: 2 }, { y: 3 });
//Use newlines to group logically related pieces of code. For example:
doSomething(x);
doAnotherSimilarThing(x);
doSomethingTotallyDifferent(y);
@adamloving
Copy link
Author

@adamloving
Copy link
Author

An exception to the "function names should start with verbs" rule are common functional idioms like _.each(), and promise.done(), or $('x').on() ... note how all those take functions as parameters.

@adamloving
Copy link
Author

Because other people have different screen, font, sizes and vision capabilities, wrap lines if longer than 80-100 columns. Keep functions shorter than 40 lines so they can be seen in one screen (and are simple enough to be understood). If functions are longer than that, refactor into short functions.

@adamloving
Copy link
Author

Glad to see my style choice matches the majority: http://sideeffect.kr/popularconvention/#javascript

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