Jump to main content
Menu

Three JavaScript Coding Styles

Coding Styles

  • As you examine JavaScript in use around the Web, you will notice that there are a variety of approaches to how code is written.
  • No approach is perfect, because each has tradeoffs.
  • Sometimes codebases use different styles.
    • This is not ideal, but it's to your benefit to be able to work with the various ways JavaScript is written.
    • It's likely that different developers worked on the codebase at different times, and each was writing JavaScript in a way that made sense to them.
  • This articles explores three approaches (three styles) for writing JavaScript.
  • These are not the only approaches / styles.

Style 1: Object Literal

Most examples on this site use an Object Literal style.

Object Literal Benefits

  • Code is easy to read.
  • Reflects the prototypal object oriented approach that is at the heart of JavaScript.
  • The syntax is the basis for JSON (JavaScript Object Notation), which is the most common approach for sending data between systems and is also frequently used for storing configuration details. Many server-side languages support JSON natively, so using this for your JavaScript simplifies integration.
  • If only one Object is used, there is only one global variable that your code has added.
  • Code outside of your Object can modify its members (properties and methods) without needing any getter / setter methods.

Object Literal Drawbacks

  • Code outside of your Object can modify its members (properties and methods) without needing any getter / setter methods. Yes, this is viewed as a negative by developers worried about some other code modifying their code. So it is both a pro and a con.
  • For some developers, even one global variable is too many.
  • If you try to access a pathway in your object that does not exist, a fatal error will occur. The solution to this is the optional chaining operator, but browser support could prove challenging.
  • Those who dislike prototypal object orientation (or do not understand it) are not fans.

Style 2: Classical Object Oriented

These are ES6 classes.

Classical Object Oriented Benefits

  • Code is easy to read.
  • Follows the syntax of other classical object oriented languages, like Java, Python, etc. You define classes and instantiate objects.
  • Updating object properties happens via getter / setter methods. The private syntax for class properties and methods forces the getter / setter usage.
  • Classes can be passed to functions and returned from functions.
  • Code within a class is automatically in Strict Mode (no need for "use strict").

Classical Object Oriented Drawbacks

  • Despite looking like other classical OO, these are just a special type of function in JavaScript.
  • Inheritance is limited, compared to other classical OO languages. It is limited to a single parent, accessed via super.
  • Classes end up in the global namespace, and whatever object(s) are instantiated also end up as globals.

Style 3: Anonymous Function

In this approach, everything is wrapped in an anonymous function.

Anonymous Function Benefits

  • There are no global variables that can result in collisions.
  • Nested functions can access variables in the function holding them; this is because nesting functions in JavaScript creates a closure.
  • Protects code from other scripts being able to modify it.
  • You can wrap your Object Literal inside of an anonymous function, which creates a closure and confers the other benefits noted.

Anonymous Function Drawbacks

  • The final sequence of parens and brackets can trip developers up - it is not the easiest code to read or get correct.
  • Instantiating multiple objects from this is not possible.
  • Garbage collection needs to be able to properly dispose of these anonymous functions.

One Example Three Ways

Object Literal Example

See the Pen Object Literal by Jason Withrow (@jwithrow) on CodePen.

Classical OO Example

See the Pen Classical Object Oriented by Jason Withrow (@jwithrow) on CodePen.

Anonymous Function Example

See the Pen Anonymous Function by Jason Withrow (@jwithrow) on CodePen.

Optional Chaining Operator

  • Object objects, and the object literal style, allow for a hierarchy to be created:
    const myObj = {
    
      actions : {
    
        doSomething : function() {
          return 'yes';
        }
    
      }
    
    };
    
  • doSomething() is accessed as myObj.actions.doSomething();
  • But what if you try to access a non-existent property as part of a path, such as myObj.otherActions.doSomething() - what happens then? It's not a happy result; you get an error.
  • The optional chaining operator (sometimes referred to as the safe traversal operator), which is a question mark before the dot, returns undefined if that part of the chain does not exist. This is preferable to an error, because the error can shut down further JavaScript processing in the main thread.
  • The revised code is myObj.otherActions?.doSomething();
  • You just need to be careful that your users have supportive browsers for the optional chaining operator - if they do not, then you've got an error being thrown because of that. It is part of ES2020, so it's a newer arrival. A polyfill is another option, if you're supporting older browsers.