JavaScript Style Guide

By Xah Lee. Date: . Last updated: .

JavaScript Best practice. Ordered roughly from most important to less.

Always Declare Variable

All use of variable should be declared.

That is, never have

x = 3

where there's no any var, let, const before it. (unless it's been declared before and you are just changing the value.)

Never use 「var」

Try to alway use const. It can be used for object, function, array.

[see JS: const Declaration]

Use let if you have variable that need to be changed.

[see JS: let Declaration]

Never use var, unless you are working in pre ES2015 JavaScript.

var is from early days of JavaScript. It has very complex and bad semantics. That is, it has complex variable scope, and name-hoisting behavior (which is not simple to understand) See:

Never Use “with” Statement

The with statement creates semantic ambiguity of code inside its curly brackets.

For example,

const y = {x:4};

with (y) {
    var x = 3;
    // do something with x
}

console.log ( y );
// { x: 3 }
// y.x is changed

The x means y.x, if y has a property x.

This means, you have to watch out whenever you use a local variable. But you may not know what property y has. Also other people editing your code may not be aware it is inside a with statement. So its prone to create errors.

Never Use ==

Never use double equal ==.

// using == is unpredicable. Always use ===

console.log( [] == "" ); // true
console.log( "" == {} ); // false
console.log( "0" == 0 ); // true
console.log( "" == 0 ); // true
console.log( 1 == true );  // true

The == does type conversion implicitly.

Use triple equal === instead.

// using == is unpredicable. Always use ===

console.log( [] === "" ); // false
console.log( "" === {} ); // false
console.log( "0" === 0 ); // false
console.log( "" === 0 ); // false
console.log( 1 === true );  // false

Always Use Semicolon

Always use semicolon. Omitting semicolon creates hard-to-find bugs.

const f = function() {
    return 3;
} // bad semicolon omission

(function() {
    return 4;
})();

// TypeError: (intermediate value)(...) is not a function

[see JS: Semicolon]

Never Use the Property named “constructor”

Never use the property key "constructor". Because its value can be anything.

Every function f has a property key "prototype".

[see JS: Property Key "prototype"]

The value of it by default is {"constructor":f} (that is, a object with a property key "constructor", with value of the function itself).

[see JS: Property Key “constructor”]

Never use the “instanceof” Operator

Never use the instanceof operator. Because, what it actually does may not be what you expect, and there are better ways to do what you want.

obj instanceof f is basically the same as f.prototype.isPrototypeOf(obj).

[see JS: “instanceof” Operator]

Lots of things can go wrong, because:

To find a object's subtype, use Object.prototype.toString.call(x).

[see JS: Determine Type of Object]

To determine if a object is in the prototype chain of another, use isPrototypeOf.

[see JS: Get/Set Prototype]

Never use the Constructor named “Array”

Never use the constructor function Array, because its behavior is very complex, depending on the number of arguments and their type.

[see JS: Array Constructor]

Use array literal expression […] instead, then use “for loop” or array method “push” to fill or add elements.

[see JS: Array.prototype.push]

Never Use the Constructor Named “Object”

Never use the constructor function Object, because its behavior is complex.

[see JS: Object Constructor]

Use literal expression {…}, or use Object.create(…).

Avoid for-in Loop

When you use

for (x in obj) {…}

It goes thru the prototype-chain of obj. That's usually not what you want.

To go thru properties, use:

[see JS: List Properties]

Or use for-of loop for iterable object.

[see JS: for-of Loop]

Avoid use the Constructor named “Function”

Avoid using the constructor function Function.

[see JS: Function Constructor]

The only use of Function is for it to generate function at run-time. Normally just use function … {…}. Or better, always use arrow function.

[see JS: Arrow Function]

Avoid Using “eval()”

Using eval is sort of meta programing. But it has several problems.

Don't Change a Object's Parent

It's recommend you don't change a object's parent. Due to how JavaScript is implemented, changing a object's parent causes major slow down.

[see JS: Change an Object's Prototype]

Avoid Using Keyword “this”

Avoid using this keyword. Because, its value is dependent on calling context in a complex way. [see JS: “this” Binding]

You can use Object.create().

Douglas Crockford, said he stopped using this and new. [see JS: Douglas Crockford the Better Parts: the Bads Parts Reconsidered]

Avoid Using Operator 「new」

Avoid using new F, because its behavior is extremely complex, and drags in all the extremely other complex parts, the keyword this, the function prototype property, and constructor property.

Douglas Crockford stopped using new, perhaps you should consider it too. JS: Douglas Crockford the Better Parts: the Bads Parts Reconsidered.

[see JS: Operator “new”]

Instead, write a function that returns a object, and or use Object.create(). This way, you can more simply and reliably specify parent object or the prototype chain. [see JS: How to Use Object.create() to Emulate Constructor?]

Avoid Using Exceptions

As a programing style in general, you might consider avoid using the {Throw Try Catch Finally}. [see JS: Throw Try Catch Finally]

Because, they are implicit goto, and are prone to be abused. Meaning, it makes it hard to understand the program flow.

Write your program to handle error cases explicitly, locally.

For more detail, See: Why I Hate Exceptions.

Avoid Using Getter and Setter Methods

Getter and setter methods are complex, and are not necessary.

[see JS: Get/Set Prototype]

Liket it? I spend 2 years writing this tutorial. Help me spread it. Tell your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

JavaScript in Depth

Basics

  1. JavaScript Basics
  2. true, false
  3. Operators
  4. Branch Control
  5. Loop
  6. Array Basics
  7. Object Basics
  8. RegExp Basics

Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment

String

  1. String Overview
  2. Template String
  3. Char, Code Unit, Codepoint
  4. String Escape Sequence
  5. Unicode Escape Sequence

Function

  1. Define Function
  2. Arrow Function ⭐
  3. Function Params
  4. “arguments” Object
  5. Rest Params ⭐
  6. Arg Default Value ⭐
  7. Arg Destructure ⭐
  8. f Declaration vs Expression
  9. Closure
  10. f call apply bind
  11. Functional Programing

Object Property

  1. Property Overview
  2. Property Key
  3. Dot vs Bracket Notation
  4. Create/Delete Property
  5. Get/Set Property
  6. Check Property Existence
  7. Access Property
  8. List Properties
  9. Property Attributes
  10. Getter/Setter
  11. Property Descriptor
  12. Symbol

Object and Inheritance

  1. Object Overview
  2. Object Type
  3. Find Object's Type
  4. Prototype Chain
  5. Create Object
  6. Object Literal Expr
  7. Create Object with Parent X
  8. Get/Set Parent
  9. Show Prototype Chain
  10. Prevent Adding Property
  11. Clone Object
  12. Test Object Equality
  13. Add Method to Prototype

Array

  1. Understand JS Array
  2. Create Array
  3. Sparse Array
  4. Array-Like Object
  5. Array How-To

Class

  1. “this” Binding
  2. What's Constructor?
  3. Property Key "prototype"
  4. Operator “new”
  5. Operator “instanceof”
  6. Property Key “constructor”
  7. Class
  8. Keyword “extends”
  9. Keyword “super”

Iterable ⭐

  1. Interface
  2. Iterable
  3. Iterator
  4. Iterator Prototype
  5. for-of Loop
  6. Spread Operator
  7. Generator
  8. Generator Function

Misc

  1. Set Object
  2. Map Object
  3. Try Catch Throw Finally
  4. Import/Export
  5. Promise
  6. Proxy
  7. ES2015 Features
  8. How to Convert ES5 to ES2015
  9. Style Guide
  10. Semicolon Rules
  11. Exclamation Before Function
  12. How to Determine Strict Mode?
  13. x.y.z Associativity
  14. Function Chain
  15. Random Number, Range, Integer, Element
  16. Timing JS Code
  17. Range Function for Array
  18. Random Array Element, Randomize Array
  19. Tagged Template String
  20. String to Number
  21. Format Number

Object Reference

  1. the Global Object
  2. Object 🙼 Object.prototype
  3. Array 🙼 Array.prototype
  4. Function 🙼 Function.prototype
  5. String 🙼 String.prototype
  6. RegExp 🙼 RegExp.prototype 🙼 RegExp Syntax
  7. Date 🙼 Date.prototype
  8. Set ⭐🙼 Set.prototype
  9. Map ⭐🙼 Map.prototype
  10. JSON
  11. Math
  12. Reflect
  13. Symbol ⭐🙼 Symbol.prototype
  14. Number 🙼 Number.prototype
  15. Boolean 🙼 Boolean.prototype

DOM How-To

  1. Basic DOM Methods
  2. Get Elements by ID, Tag, Name, Class, CSS Selector
  3. Change CSS
  4. Change Node Content
  5. Create/Insert Node
  6. Remove Node
  7. Get Element's Attribute Value
  8. Set Element's Attribute Value
  9. Remove Element's Attribute Value
  10. List/Add/Remove Class Attribute
  11. Add/Remove Event Handler
  12. Navigate DOM Tree

DOM Overview

  1. Browser Window Object, Document Object Model
  2. Intro to Event-Based Programing
  3. JavaScript Load Order
  4. What is Live Object
  5. NodeList vs HTMLCollection
  6. DOM: Whitespace Nodes

Basic DOM Methods

  1. Basic DOM Methods
  2. Node Type, Name, Value
  3. Navigate DOM Tree

HTML Form

  1. HTML Form
  2. Visit URL in a New Window
  3. Instant Field Validation
  4. Input Field Validation
  5. HTML: Input Range Slider

DOM How To

  1. Encode URL, Escape String
  2. Browser Info, Navigator Object
  3. Get URL (window.location)
  4. Web Cookies
  5. Web Storage
  6. Find Window Width
  7. Find Element Width
  8. WebSocket

Web Scripting Examples

  1. Disable Right Click
  2. document.write
  3. Image Rollover
  4. Pop-up New Window
  5. Digital Clock
  6. Stopwatch
  7. Fade a Element
  8. Fade a Element Using CSS Transition
  9. Shake Element
  10. How to Create Tooltip
  11. Falling Snow Effect
  12. JavaScript: Floating Box Following Scroll

DOM Misc

  1. Value of “this” in Event Handler
  2. Event Delegation
  3. Get Current Script Tag
  4. insertAfter Element
  5. Randomize List
  6. create Document Fragment
  7. innerHTML, nodeValue, textContent, innerText?

jQuery

  1. jQuery Basics
  2. jQuery() vs querySelectorAll()
  3. Write JQuery Plugin

node.js