A mostly reasonable approach to JavaScript

For the ES5-only guide click here.
- Types
- References
- Objects
- Arrays
- Destructuring
- Strings
- Functions
- Arrow Functions
- Constructors
- Modules
- Iterators and Generators
- Properties
- Variables
- Hoisting
- Comparison Operators & Equality
- Blocks
- Comments
- Whitespace
- Commas
- Semicolons
- Type Casting & Coercion
- Naming Conventions
- Accessors
- Events
- jQuery
- ECMAScript 5 Compatibility
- ECMAScript 6 Styles
- Testing
- Performance
- Resources
- In the Wild
- Translation
- The JavaScript Style Guide Guide
- Chat With Us About Javascript
- Contributors
- License
-
1.1 Primitives: When you access a primitive type you work directly on its value.
stringnumberbooleannullundefined
const foo = 1; let bar = foo; bar = 9; console.log(foo, bar); // => 1, 9
-
1.2 Complex: When you access a complex type you work on a reference to its value.
objectarrayfunction
const foo = [1, 2]; const bar = foo; bar[0] = 9; console.log(foo[0], bar[0]); // => 9, 9
- 2.1 Use
constfor all of your references; avoid usingvar.
Why? This ensures that you can't reassign your references (mutation), which can lead to bugs and difficult to comprehend code.
```javascript
// bad
var a = 1;
var b = 2;
// good
const a = 1;
const b = 2;
```
- 2.2 If you must mutate references, use
letinstead ofvar.
Why?
letis block-scoped rather than function-scoped likevar.
```javascript
// bad
var count = 1;
if (true) {
count += 1;
}
// good, use the let.
let count = 1;
if (true) {
count += 1;
}
```
-
2.3 Note that both
letandconstare block-scoped.// const and let only exist in the blocks they are defined in. { let a = 1; const b = 1; } console.log(a); // ReferenceError console.log(b); // ReferenceError
-
3.1 Use the literal syntax for object creation.
// bad const item = new Object(); // good const item = {};
-
3.2 If your code will be executed in browsers in script context, don't use reserved words as keys. It won't work in IE8. More info. It’s OK to use them in ES6 modules and server-side code.
// bad const superman = { default: { clark: 'kent' }, private: true, }; // good const superman = { defaults: { clark: 'kent' }, hidden: true, };
-
3.3 Use readable synonyms in place of reserved words.
// bad const superman = { class: 'alien', }; // bad const superman = { klass: 'alien', }; // good const superman = { type: 'alien', };
- 3.4 Use computed property names when creating objects with dynamic property names.
Why? They allow you to define all the properties of an object in one place.
```javascript
function getKey(k) {
return `a key named ${k}`;
}
// bad
const obj = {
id: 5,
name: 'San Francisco',
};
obj[getKey('enabled')] = true;
// good
const obj = {
id: 5,
name: 'San Francisco',
[getKey('enabled')]: true,
};
```