Categories
JavaScript Best Practices

JavaScript Best Practices — Objects and Invalid Syntax

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

Objects Must Contain a Getter When a Setter is Defined

Objects should have a getter when a setter is defined.

A setter without a getter isn’t very useful, so we should add one.

For instance, we write:

const person = {
  set name (value) {
    this._name = value
  },
  get name () {
    return this._name
  }
}

instead of:

const person = {
  set name (value) {
    this._name = value
  }
}

Constructors of Derived Classes Must Call super

We should call super in derived classes.

For instance, we should write:

class Cat extends Animal {
  constructor () {
    super()
    this.legs = 4;
  }
}

We’ll get an error if we don’t call super before setting properties in our class as we did in the example.

Use Array Literals Instead of Array Constructors

The Array constructor just adds extra complexity to our array declarations.

It does 2 different things.

If it has one argument passed into it, then it returns an empty array with the number of empty slots in the array.

Otherwise, it returns an array with the arguments we passed in.

Therefore, we should just use array literals.

For example, we write:

const nums = [1, 2, 3];

instead of:

const nums = new Array(1, 2, 3);

Don’t Use arguments.callee and arguments.caller

We shouldn’t use any properties in the arguments object, including the callee and caller properties.

They make code optimizations impossible. Also, they’re deprecated and are forbidden in strict mode.

Therefore, we should never use them.

Don’t Modify Variables of Class Declarations

If we have a class, then we shouldn’t assign it to something else.

This will avoid lots of confusion.

For instance, we shouldn’t have code like:

class Dog {}
Dog = 'woof';

That’s just confusing.

Avoid Modifying Variables Declared Using const

Reassigning a const variable with a new value will give us an error.

Therefore, we shouldn’t do that.

For instance, we shouldn’t have:

const score = 100;
score = 125;

Instead, we can remove the second line or create a new variable an assign the value to it.

No Constant Expressions in Conditional Statements

Constant expressions aren’t very useful in conditional statements.

This is because they always evaluate to the same thing, so it’s useless to have the conditional statement.

For example, we shouldn’t have code like:

if (false) {
  // ...
}

The code inside the block never runs since we have false as the condition.

However, we can have them in loops:

while (true) {
  // ...
}

since we may want infinite loops.

No Control Characters in Regular Expressions

We shouldn’t have control characters in regexes.

They are invisible and they’re rarely used in JavaScript strings.

Therefore, it’s probably a mistake that we include them.

So we shouldn’t have code like:

const re = /x1f/;

No debugger Statements

The debugger statement is used for adding breakpoints in our code so that we can inspect the variables.

However, we should remember to remove them when we’re done with them so that our app won’t pause when it’s in production.

No delete Operator on Variables

The delete operator is used for removing properties.

Therefore, they shouldn’t be used on variables.

So we shouldn’t write:

let foo;
delete foo;

No Duplicate Arguments in Function Signatures

We should never have duplicate arguments in function signatures.

It’s invalid syntax and will give us unexpected results.

For example, we shouldn’t write:

function sum (a, a, b) {
  // ...
}

Instead, we write:

function sum (a, b, c) {
  // ...
}

No Duplicate Name in Class Members

We shouldn’t have 2 class members with the same name.

That will yield unexpected results.

For example, we shouldn’t have:

class Cat {
  meow() {}
  meow() {}
}

We should name them with different names.

Conclusion

We shouldn’t use operators in invalid ways in our JavaScript code.

Also, we shouldn’t have duplicate expressions where we shouldn’t have them.

Any extraneous characters and debugger statements should be removed from our code.

Categories
JavaScript Best Practices

JavaScript Best Practices — Operations

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

Place the ? : in Ternary Operators on their Own Lines if the Expressions are Long

We should place ? and : on their own line if they expressions are long.

For instance, we can write:

const apiUrl = env.development  
  ? 'localhost'  
  : 'http://www.api.com'

or:

const apiUrl = env.development ? 'localhost' : 'http://www.api.com'

Write Each var Declaration in their Own Statement

To make the declaartions clear, we should put them onto their own line.

For example, we write:

var foo = true  
var bar = true

instead of:

var foo = true, bar = true;

or:

var foo = true,   
    bar = true;

Now we know that foo and bar are both declared with var .

Wrap Conditional Assignments with Additional Parentheses

We should wrap conditional assignments with additional parentheses to make readers clear of our intentions.

For example, we write:

while ((m = text.next(expr))) {  
  // ...  
}

instead of writing:

while (m = text.next(expr)) {  
  // ...  
}

This way, readers will know that the assignment is intentional.

Add Spaces Inside Single Line Blocks

We should add spaces inside single-line blocks for better readability.

For example, instead of writing:

function foo () {return true}

We write:

function foo () { return true }

Use camelCase When Naming Variables and Functions

Using camelCase for variables and functions is commonly accepted convention, so we should use it in our code for consistency.

For example, we should write:

let myVar = 'hello';

or:

function myFunction () { }

Trailing Commas

Trailing commas may be removed to maintain compatibility between browsers.

For example, we can write:

const obj = {  
  msg: 'hello'  
}

which is more compatible than:

const obj = {  
  msg: 'hello',  
}

Commas Must be Placed at the End of the Current Line

We should place commas at the end of the current line.

It’s much less confusing if we do that.

For example, we shouldn’t write:

const obj = {  
  foo: 'foo'  
  ,bar: 'bar'  
}

Instead, we write:

const obj = {  
  foo: 'foo',  
  bar: 'bar'  
}

The Dot Should be on the Same Line as the Property

The dot should be placed on the same line as the property to indicate that we’re accessing it.

For instance, we write:

console  
  .log('hello')

instead of writing:

console.  
  log('hello')

Files Should End with a New Line

We should add a new line to the end of each file so that they can be concatenated properly.

Likewise, they can be appended to properly if we have an empty line at the end of the file.

Outputting the file to the terminal with a new line also won’t interfere with the shell prompt.

Therefore, we should have a new line at the end of each file.

No Space Between Function Identifiers and Their Invocations

There should be no space between function identifiers and their invocation.

For example, we write:

console.log('hi')

instead of:

console.log ('hi')

Add a Space Between Colon and Value in Key-Value Pairs

We should add a space between the colon and value in key-value pairs for readability.

For example, we write:

const obj = { 'key': 'value' }

Photo by Han Chenxu on Unsplash

Constructor Names Must Begin with a Capital Letter

According to commonly accepted JavaScript conventions, constructor names must begin with a capital letter.

Therefore, we should have that in our code.

For instance, we write:

function Animal () {}  
const cat = new Animal();

Constructor with no Arguments Must be Invoked with Parentheses

We should invoke a constructor with no arguments with parentheses.

Although we’re allowed to invoke constructors with no arguments without parentheses in JavaScript, we shouldn’t do it.

This causes confusion.

So we should write:L

const dog = new Animal()

instead of:

const dog = new Animal

Conclusion

We should add spacing in our code for better readability.

However, we should add them where they’re appropriate.

Also, we should follow common conventions.

Categories
JavaScript Best Practices

JavaScript Best Practices — Basic Syntax

Like any kind of app, JavaScript apps also have to be written well. Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

Indentation

We should have 2 spaces for indentation. This minimizes typing while maintaining visibility.

For instance, we write:

function hello (name) {
  console.log('hi')
}

Single Quotes for Strings

Single quotes are good for delimiting strings since we don’t have to press the shift key as we do with typing double-quotes.

For instance, we can write:

'hello world'

to save us some effort when typing.

No Unused Variables

Variables we don’t use are useless, so we shouldn’t have them.

Add a Space After Keywords

A space after keywords is always useful since it makes reading our code easier.

So we should add them:

if (condition) { ... }

Having no spaces make things hard to read.

Add a Space Before a Function Declaration’s Parentheses

We should add a space before a function declaration’s parentheses for better readability,

For example, we should write:

function foo (arg) { ... }

Always Use === Instead of ==

=== doesn’t to automatic data type conversions with complex rules before comparing its operands.

Therefore, this makes === much more preferable than == .

It’ll help us avoid lots of bugs by using it.

So we write:

if (name === 'james')

instead of:

if (name == 'james')

Likewise, we should use !== instead of != for inequality comparison for the same reason.

For example, we write:

if (name !== 'John')

instead of:

if (name != 'John')

However, we can use == to check for null and undefined in one expression.

For instance, we can write:

if (foo == null)

to do that.

Infix Operators Must be Spaced

We should space out any infix operators like = or arithmetic operators.

For instance,e we shouldn’;r write:

let x=2;

Instead, we write:

let x = 2;

Likewise, we should write:

let message = 'hello, ' + name + '.'

instead of:

let message = 'hello, '+name+'.'

This way, we can read the code a lot easier, especially if we have lots of operators in our expression.

Commas Should Have a Space Character

We should have a space character after a comma.

For example, we should write:

const list = [1, 2, 3]

or:

const greet = (name, options) => { ... }

instead of:

const list = [1,2,3]

or:

const greet = (name,options) => { ... }

Keep else Statements on the Same Line as their Curly Braces

We should keep else in the same line as their curly braces.

For example, we should write:

if (condition) {
  // ...
} else {
  // ...
}

instead of:

if (condition) {
  // ...
}
else {
  // ...
}

It saves some space while maintaining readability.

Use Curly Braces for Multiline Statements

We should use curly braces for if statements so we don’t get confused about them.

For instance, we can write:

if (options.foo) console.log('done')

or:

if (options.foo) {
  console.log('done')
}

However, we shouldn’t write:

if (options.foo)
  console.log('done')

since it’s deceptive where the if block starts or ends.

Always Handle err Function Parameter

If a callback has an err parameter, then we should handle it if it’s defined.

For example. we write:

run(function (err) {
  if (err) throw err
  console.log('done')
})

If err is defined then we throw it.

What we shouldn’t do if ignore it and pretend that nothing happened.

Declare Browser Globals with a global Comment

To make sure that we aren’t defining undeclared global variables, we should add a comment or reference the global object to access the global variable.

For example, we write:

/* global alert */

alert('hi')

We can also write:

window.alert('hi');

window is the global object in the browser, so we should write that out explicitly.

No Multiple Blank Lines

It’s useless to have multiple blank lines, so we should just keep one maximum and remove the rest.

We write:

const value = 'hello world';
console.log(value);

instead of:

const value = 'hello world';

console.log(value);

Conclusion

We should indicate global variables if we’re using them.

Also, we should use === or !== for comparisons in most cases.

Indentation and spaces make reading code easier.

Categories
JavaScript Best Practices

JavaScript Best Practices — Bad Expressions

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

No Whitespace Between Spread Operators and their Expressions

We shouldn’t have any whitespace between spread operators and their expressions.

For instance, instead of writing:

fn(... args)

We write:

fn(...args)

Semicolons Must Have a Space Character After and no Space Before

Semicolons should have a space character after it and no space before as commonly accepted in JavaScript.

For instance, instead of writing:

for (let i = 0 ;i < arr.length ;i++) {...}

We write:

for (let i = 0; i < arr.length; i++) {...}

Have a Space Character Between Blocks

If we’re creating a block, then we should have a space character before it.

For instance, instead of writing:

if (cond){...}

We write:

if (cond) {...}

No Space Inside Parentheses

We shouldn’t have spaces inside parentheses.

For instance, instead of writing:

getName( person )

We write:

getName(person)

Unary Operators Must have Space After it

We should have a space character after unary operators so we can read them.

Also, we don’t want to join words together.

For instance, instead of writing:

typeof!cond

We write:

typeof !cond

Use Spaces Inside Comments

We should have spaces inside JavaScript comments.

For instance, instead of writing:

//comment

We write:

// comment

For multiline comments, we shouldn’t write:

/*comment*/

Instead, we write:

/* comment */

No Spacing in Template Strings

We shouldn’t have spaces at the beginning or the end of expression in template strings.

For instance, instead of writing:

const message = `hi, ${ name }`

We write:

const message = `hi, ${name}`

To Check for NaN, we Should Use isNaN

We can’t use the === to compare NaN since NaN isn’t considered to be the same as itself.

Instead, we need to use the isNaN function to check for NaN .

So instead of writing;

if (price === NaN) { }

We write:

if (isNaN(price)) { }

typeof Must be Compared to a String

The typeof must be compared to a valid string.

Make sure that we don’t have typos in the string.

For instance, we shouldn’t write:

typeof name === 'undefimed'

when we actually mean:

typeof name === 'undefined'

Immediately Invoked Function Expressions (IIFEs) Must be Wrapped

We should wrap IIFEs with parentheses so we make it clear that we’re calling the function immediately after it’s defined.

For instance, we should write:

const getName = (function () { }())

or:

const getName = (function () { })()

or:

const getName = (() => { })()

yield Expressions Must Have a Space Before and After

When we’re calling a generator function from another generator function, we need the yield * keyword.

We should write it like that for consistency with JavaScript conventions.

For instance, we write:

yield * foo();

No Yoda Expressions

We should have the value we’re comparing as the right operator so that we can them easier.

It’s more like regular human speech

For instance, we write:

if (age === 2) { }

instead of:

if (2 === age) { }

Semicolons

We should have semicolons to avoid automatic semicolon insertion in unexpected places.

For instance, we write:

window.alert('hi');

Never Start a New Line with Characters that we Don’t Expect to Start a Line With

We shouldn’t have characters like parentheses, brackets, semicolons, commas, etc. to start a line with even though they’re valid.

For instance, we shouldn’t write code like:

;(function () {
  window.alert('ok')
}())

Instead, we write:

(function () {
  window.alert('ok')
}())

Conclusion

We shouldn’t write code that most people don’t expect.

Also, we should write code that reads naturally as programmers.

We also shouldn’t have useless whitespace in our code.

Categories
JavaScript Best Practices

JavaScript Best Practices — Simple Expressions

Like any kind of apps, JavaScript apps also have to be written well.

Otherwise, we run into all kinds of issues later on.

In this article, we’ll look at some best practices we should follow when writing JavaScript code.

No Ternary Expressions When Simpler Alternatives Exist

We shouldn’t write ternary expressions when simpler alternatives exist.

For instance, if we have:

let score = val ? val : 0

Then we should write:

let score = val || 0

instead, since they do the same thing.

If val is falsy, then 0 will be returned in both examples.

No Unreachable Code After return, throw, continue, or break Statements

If we write those statements, then we should make sure that the code that comes after it is still reachable in some cases.

For instance, we shouldn’t have code like:

function foo () {
  return true;
  console.log('never');
}

The console log isn’t reachable since it comes after a return statement that always runs.

No Flow Control Statements in finally Blocks

We shouldn’t have flow control statements in finally blocks.

JavaScript suspends flow control statements of try and catch blocks until the execution of the finally block finishes.

So when return , throw , break , or continue are used in finally , the control flow statements in try or catch are overwritten.

Therefore, unexpected behavior may result.

So we shouldn’t write code like:

try {
  // ...
} catch (e) {
  // ...
} finally {
  return 1;
}

The Left Operand of Relational Operators Shouldn’t be Negated

If we have code like:

if (!key in obj) {}

Then only key is negated, which is probably a mistake.

Instead, we should negate the whole expression:

if (!(key in obj)) {}

Avoid Unnecessary Use of call and apply

We only need to use call and apply to change the value of this inside a function.

Other than that, we can use the spread operator to spread array entries into arguments instead of calling apply .

So instead of writing:

sum.call(null, 1, 2, 3)

We write:

sum.call(1, 2, 3)

or:

sum.call(...nums)

Don’t Use Unnecessary Computed Property Keys on Objects

We shouldn’t use unnecessary computed property keys on objects.

They are useless and can be simplified.

For instance, instead of writing:

const user = { ['name']: 'james' };

We write:

const user = { name: 'james' };

No Unnecessary Constructor

If we have an empty constructor in our class, then we don’t need it.

So we shouldn’t write:

class Car {
  constructor () {
  }
}

as JavaScript will provide an empty constructor for us.

No Unnecessary Use of Escape Characters

We shouldn’t escape characters in a useless way.

Therefore, we shouldn’t write code like:

let message = 'hello'

Don’t Rename Import, Export, and Destructured Assignments to the Same Name

There’s no point in renaming imports, exports, and restructured assignments to the same name.

Therefore, we shouldn’t do this.

For instance, instead of writing:

import { foo as foo } from './config'

Instead, we just write:

import { foo } from './config'

No Whitespace Before Properties

Whitespace before properties are useless and don’t follow commonly accept JavaScript code formatting conventions.

Therefore, we shouldn’t have them.

For instance, instead of writing:

user .password

We write:

user.password

No with Statements

We should never use with statements.

They are disallowed in strict mode.

Also, they create variables with confusing scopes.

Therefore, we should never write things like:

with (obj) {...}

Have Consistency in Newline Between Object Properties

When we defimen object literals, we should either have newlines after each property.

Or we can puyt all the properties of the same line if they won’t overflow the page.

For instance, we either write:

const user = { name: 'jame', age: 30, password: '123' }

Or we write:

const user = {
  name: 'jame',
  age: 30,
  password: '123'
}

No Padding within Blocks

We shouldn’t have padding within blocks.

For instance, we shouldn’t write:

if (user) {

  const name = getName()

}

Instead, we write:

if (user) {
  const name = getName()
}

Conclusion

We shouldn’t have useless whitespaces.

Also, we should format object consistency when it comes to newlines.

We also should make sure that we don’t have any unreachable code in our blocks.