JavaScript Best Practices: Syntax

Welcome to Part 2 of this review of the new Pluralsight course JavaScript Best Practices by Jonathan Mills.

jonathan-mills-v2

Jonathan is a JavaScript and Node.js expert working mostly in the MEAN Stack with individuals and companies to help build their technical skills to cope with the constantly changing landscape of software development.

He is also an ASP.NET insider and an international speaker focusing on JavaScript both in the browser and on the server.

Also in this series:

Part 1: Why Best Practices
Part 2: Syntax
Part 3: Behaviors
Part 4: Async Patterns
Part 5: Production Code

In this second part, we look at the JavaScript syntax, which can be a little painful for developers who are used to working in another language. JavaScript works differently, and it’s important to understand and appreciate these differences.

JavaScript Best Practices: Syntax

Semicolons

Jonathan says this is one of the most contentious of conversations on JavaScript syntax.

Lot of people say that semicolons are optional in JavaScript, but Jonathan argues that this isn’t entirely correct, quoting from the EcmaScript Standards:

“Certain ECMAScript statements (…) must be terminated with semicolons.

For convenience, however, such semicolons may be omitted from the source text in certain situations.

These situations are described by saying that semicolons are automatically inserted…”

You can see the Github thread or see Mike Wilcox’s Great Semicolon Debate presentation for a humorous look at the whole story.

Automatic Semicolon Insertion

Jonathan describes the three rules of ASI, based on the EcmaScript Standards, and using some simple examples. The following syntax is detected as having missing semicolons:

var a = 12
var b = 13

if(a){console.log(a)}

console.log(a+b)

The ASI rules add the semicolons in for us:

var a = 12;
var b = 13;

if(a){console.log(a);}

console.log(a+b);

Based on this example you might think that we should always rely on the compiler to insert the semicolons for us, however there are situations where ASI will not add the semicolons for us. Here is one of the examples that Jonathan gives:

var a = 12
var b = 13
var c = b + a

[‘menu,’items’,’listed’].forEach(function (element){
console.log(element)
})

No semicolon will get added before the [ character.

There is also the possible problem of ASI inserting a semicolon where we don’t expect it to! Jonathan explains that there are some keywords that are classified as restricted production:

  • continue
  • break
  • return
  • throw

If there’s a line terminator after any of these then a semicolon is inserted. So we need to be careful that we don’t write code like this:

return
{
hi: ‘hi’
}

Jonathan’s rule is

“Use semicolons in conjunction with JSHint (or ESLint) to prevent potential issues” – Jonathan Mills

This has the following benefits:

  1. Consistency with other languages
  2. Prevents the .01% of issues…

Linting

A linter will scan our code to detect potential problems and errors.

Jonathan looks at some different linters that are available, beginning with the original linter, JS Lint, which was created by Douglas Crockford in 2002.

JS Hint is a fork of JS Lint which is much more configurable and has built in package support.

ES Lint is the most recent popular linter. It has custom rules support and lots of configuration options.

Because ES Lint is more complicated for beginners, Jonathan describes the various ways that we can get JS Hint up and running on our machine.

  1. We can use JS Hint in the browser by pasting our code into jshint.com
  2. Or we can also use JS Hint with the brackets editor by installing the JS Hint plugin.
  3. Or we can invoke JS Hint at the command line.

Curly Braces

We should put our opening curly braces on the same line, and Jonathan explains why here.

Equality

An explanation of == and ===

Developers can sometimes get themselves into trouble by using == without fully understanding how it works.

The === syntax works more similarly to how developers are used to seeing == work in many other languages.

Jonathan recommends using === as the default, and using typeof undefined to safely see if a variable exists.

Configuring JS Hint

We see how to enable the eqeqeq rule in JS Hint.

For all configuration options see jshint.com/docs/options

Variables

This lesson explains variable hoisting:

“Hoisting is JavaScript’s default behavior of moving all declarations to the top of the current scope”

To make the ECMAScript standards easier to parse, Jonathan splits the relevant paragraph out into two piece:

  1. variables are created when their containing lexical environment is instantiated
  2. …and are initialized to undefined when created.

The point I found most useful is Jonathan emphasizing that the variables don’t really get moved to the top. I’ve heard many people talk about variables getting hoisted up to the top of the function, but this just isn’t true.

We see an example of myVariable being initialized both inside and outside of a function. Which value gets logged to the console: 10? 25? or undefined?

Jonathan recommends putting all of your variable declaration at the top of your scope. This is the same advice that Douglas Crockford gives in his book “JavaScript: The Good Parts”.

Functions

There are two ways to create a function:

  1. function declarations
  2. function expressions.

We see an example of sloppy use of a functional expression, assigning a function value to a variable called expression only after it has been invoked. This gives the error:

TypeError: expression is not a function

Jonathan warns against heavy use of function expressions. In my experience, creating lots of function expressions works well as long as it is done inside of a containing object (i.e. in their own scope).

Finally Jonathan recommends declaring variables first, then functions, and finally code that calls the functions (he calls this run code).

We see that this applies to both the global and local scope.

Continue to Part 3 – Behaviors

Related Pluralsight Courses

Clean Code: Writing Code For Humans by Cory House

Advanced JavaScript by Kyle Simpson

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s