Categories
JavaScript Best Practices

JavaScript Best Practices — Things We Need to Learn

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.

Learn About Scopes

We should learn about scopes of variables and functions.

Variable scopes should be easy now with let and const variables.

They’re only accessible within the block so there’s no ambiguity.

Also, we should know what’s accessible from modules.

Only things that are exported can be imported.

The tricky ones are var variables and functions declares with the function keyword.

var is function scoped so it’s available throughout a function.

function declarations can be hoisted.

So functions like:

function foo(){
  //...
}

can be called before they’re defined in the code.

Use the Fastest Way to Loop Through Variables

The fastest way to loop through variables if the good old for loop.

So we write:

let arrayLength = array.length;
for(let i = 0 ; i < arrayLength; i++) {
   let val = array[i];
}

to loop through items.

However, for convenience, the for-of loop and forEach are also good ways to loop through items without sacrificing performance too much.

If we need to map data, we use map .

If we need to return a new array that has data that matches a given condition, we use filter .

There’s also the while loop to loop through data.

Don’t Do Too Much Nesting

Too much nesting is hard to read.

This also means they’re hard to change and debug.

For example, we shouldn’t have things like:

firstFunction(args, () => {
  secondFunction(args, () => {
    thirdFunction(args, () => {
      //...
    });
  });
});

The deeper the nesting, the harder it is to work with, so we should avoid something like this.

Beware of the DOM

If we’re creating client-side JavaScript apps, then we need to manipulate the DOM.

It’s a good idea to know how to add, edit, and remove elements from the DOM.

There’re also many kinds of nodes like text and comment nodes that we’ve to be aware of in addition to element nodes.

Event propagation is also something to think about.

Use the Best Libraries and Frameworks

The top client-side JavaScript frameworks are React with some additional libraries, Angular, and Vue.

React with React Router can be considered a framework.

There’s also Svelte, which is up and coming.

The concepts are transferable between them so if we learn one, we can learn the other,

They all have a component-based architecture, so they’re similar.

Also, there are many libraries built for each of them.

Have Efficient Configuration and Translation

We should put all the configuration and translations in one location so that we can use them everywhere.

This way, we only have to change them in one place if we need to change it.

Reduce Access to Variables and Properties

If we don’t need to access variables, then we should avoid it.

For instance, with a for loop, we can cache the array length to a variable outside the for loop.

Instead of writing:

let names = ['mary', 'james', 'may'];
for (let i = 0; i < names.length; i++) {
  greet(names[i]);
}

We write:

let names = ['mary', 'james', 'may'];
let length = names.length;
for (let i = 0; i < length; i++) {
  greet(names[i]);
}

Don’t Trust Any Data

We shouldn’t trust any data from anywhere.

Therefore, we should validate any input values and check for data from other sources like APIs.

This way, we only work with exactly what we need and avoid any security issues with malicious data.

Use Arrow Functions

Arrow functions are great.

It can be used if we aren’t creating a constructor function.

If we don’t need it to bind to its own this , then we can also use it.

For instance, we can write:

const foo = () => console.log('hello');

It’s shorter and less confusing because it doesn’t bind to its own this .

Use Template Literals

Template literals are much better than concatenation since it’s much easier to read.

And we can put any expressions in them.

For example, instead of writing:

'hello '  + name;

We write:

`hello ${name}`;

Template literals are always delimited by backticks instead of single or double-quotes.

Conclusion

We should use recent features of JavaScript like template literals and arrow functions.

Also, we got to learn about scopes and this .

Categories
JavaScript Best Practices

JavaScript Best Practices — Types and This

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.

Beware of Automatic Type Conversions

We should be aware of automatic data type conversions.

For example, we can assign any values to variables we want.

We can write something like:

let text = "james";  
text = 5;

It’s easy to change the type of variables in JavaScript.

However, we can use language extensions like TypeScript and Flow to restrict the data types of variables.

Don’t Declare Unnecessary Variables

If we aren’t using a variable, then we should remove it.

The more variables are declared, the more space they take.

For example, instead of writing:

const topBar = sidebar.querySelector('#topbar');  
const paragraph = bar.querySelector('p');  
paragraph.textContent = 'bar';

We didn’t use the the topBar variable, so we shouldn’t remove it.

We can just write;

bar.querySelector('p').textContent = 'bar';

Use Parameter Defaults

To make sure that a parameter always has a value, we should set the value of the parameter.

For example, we can write:

function logNumber(num = 100) {  
  console.log(num);  
}

This is much shorter than the old way, which is:

function logNumber(num) {  
  if (num === undefined) {  
    num = 25;  
  }  
  console.log(num);  
}

With default parameters, we don’t have to assign the parameter to a new value directly.

End Switches with Defaults

If we have switch statements, we should end them with a default clause so that we do something if none of the values match.

For instance, we write:

switch(type) {  
  case 1:  
    // something  
  case 2:  
    // something else  
  default:  
    // do something  
}

In the default clause, we can handle errors or do some default action.

eval() Is Bad

eval is definitely bad.

Running code from a string is a big security risk.

And the code can’t be optimized and hard to debug.

Don’t Use new Object()

The Object constructor don’t bring us much benefit.

It’s only longer.

We can use {} instead of new Object() .

The same advice applies to primitive value constructors.

For example, instead using new String() , we write '' .

Instead of using new Number() , we use numver literals.

And instead of new Boolean() , we use true or false .

Instead of using the Array constructor, we use [] .

However, it’s still handy for creating artays with the given numver of empty slots.

With regex, we use the regex literal like /abc/ instead of new RegExp() .

And instead of using new Function() to create our function, we use function(){} or () => {} to create it.

The code is shorter without the constructors.

And in the case of the primitive constructors, the type will be the actual type of the data instead of 'object' if we check it with typeof .

It’s also slightly faster.

Comment Our Code

We can comment on our code so explain things that aren’t described by the code.

Use Shortcut Notation When It Makes Sense

We can use shortcut notations in many cases.

For example, instead of writing:

let level;  
if (score > 200){  
  level = 2;  
} else {  
  level = 1;  
}

We can write:

let level = (score > 200) ? 2 : 1;

We use the ternary operator to check the condition and assign the value accordingly.

And instead of writing:

let price;  
if (discount){  
  price = discount;  
} else {  
  price = 120;  
}

We write:

let price = discount || 120;

If discount is truthy then it’ll be returned and assigned. Otherwise, 120 is returned and assigned.

Have One Function Per Task and Make Our Code Modular

Our code should be divided into smaller parts so that we can work with them easier.

Functions should do one thing so that we won’t be confused with they do.

This also makes it easier to test and debug.

Our code should be modular for the same purpose.

We can divide them into modules.

Learn About This

this is an important keyboard to understand. It can take on different values depending on where they are.

In a method inside the object, this is the object.

If it’s in a class, then it’s the class instance.

If it’s in a prototype function, then it’s the constructor instance.

We shouldn’t know this.

Conclusion

We should use features like parameter default values and default switch case.

And avoid things like useless constructors.

We should also learn about this , type conversion, and more.

Categories
JavaScript Best Practices

JavaScript Best Practices — Styles

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.

Stick to a Strict Coding Style

We should stick to a consistent coding style for consistency.

This will reduce confusion and make our code portable between environments.

Use Strict Mode

Strict mode stops us from doing many things we shouldn’t do with javascript code like assigning values to values like undefined or null .

Also, we can’t multiple parameters with the same name.

The with statement is also not allowed with strict mode.

arguments and eval also can’t be modified.

These are very good changes that comes with strict mode.

So we should always use it.

Fortunately, strict mode is enabled by default with modules.

Use Linting

We should use ESLint for linting.

It’ll help us stick to a strict coding style.

Also, it can be used to check for errors and security issues.

Read Code Style Guides

Airbnb, Google, and other companies have their own style guides.

There’s also the Standard.js style guide, which we can follow.

There’re ESLint plugins to add those rules to our set of linting rules.

For instance, Airbnb has one.

Avoid Global Variables

We should definitely avoid using global variables.

They may be overwritten by anything so we should avoid them.

One exception is that we need to use global variables built into browsers like window or document so we can work with them.

However, we definitely shouldn’t define our own.

So we write nothing like:

window.x = 1;  
x = 2;

Prioritize Access to Local Variables

We should define variables that are in local scope as much as possible.

This is possible with block scope keywords like let or const .

They are only available within the block, so we won’t have any confusion with where they’re available.

We can use them by writing:

let x = 1;  
const y = 2;

Declarations on Top

If we’re declaring variables, we would keep them on top to make them easier to find.

It also reduces the chance that we declare them again accidentally.

Initialize Variables

We should initialize variables so that we won’t forget to do that later.

For example, we should write:

let x = 1;

This isn’t a problem with const since it’s always declared with a value.

Make Identifiers Understandable

If we’re creating variables, objects, functions, etc., we should make the names understandable so that we can work with them.

For instance, instead of writing:

let a, b, c, asdf;

We write names like:

let numApples, numOranges;

Use === Comparison

We should use === for comparisons since it doesn’t convert the type of the variable to something different before comparing them.

== does automatic data type conversion and the rules are complex, so we should avoid that.

Likewise, we should use !== for inequality comparisons for the same reason.

It’s not worth saving one character.

Conclusion

We should use strict style and === for comparisons.

Enabling strict mode is also a great idea.

Categories
JavaScript Best Practices

More JavaScript Best Practices for Beginners

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.

Use {} Instead of New Object()

We should use object literals instead of new Object() .

The constructor has no benefits over object literals and it’s longer.

Instead of writing:

let o = new Object();
o.name = 'james';
o.lastName = 'smith';
o.greet = function() {
   console.log(this.name);
}

We write:

const o = {
   name: 'james',
   lastName = 'smith',
   someFunction() {
      console.log(this.name);
   }
};

We can write:

const o = {};

to create an empty object.

Use [] Instead of New Array()

The Array constructor is longer and doesn’t bring much benefit.

However, we can create an array with a given number of empty slots with it.

So we can use it with one numerical argument to create an empty array with the number of slots.

Other than that, we use array literals.

For example, instead of writing:

const a = new Array();
a[0] = "james";
a[1] = 'smith';

We write:

const a = ['james', 'smith'];

To create an empty with the Array constructor, we write:

const a = new Array(10);

This creates an empty array with 10 slots.

Omit the Keyword and Use Commas Instead

If we have to declare a long list of variables, we can use commas to separate them.

For example, we can write:

let foo = 'some string',
  bar = 'another string',
  baz = 'one more string';

instead of:

let foo = 'some string';
let bar = 'another string';
let baz = 'one more string';

It’s shorter so it saves some typing.

Always Use Semicolons

We should use semicolons so that JavaScript won’t insert it for us.

This way, we can avoid errors.

So instead of writing:

const someItem = 'some string'
function foo() {
  return 'something'
}

We write:

const someItem = 'some string';
function foo() {
  return 'something';
}

“For in” Statements

If we’re using the for-in loop, we should use hasOwnProperty to check if the property is a non-inherited property of the object we’re looping through.

For example, we can write:

for (let key in object) {
   if (object.hasOwnProperty(key)) {
      //...
   }
}

We call hasOwnProperty on the object with eh key as the argument to check.

Use Timer Feature to Optimize Our Code

We can use the console.time and console.timeEnd function to check the timing of the code.

For example, we can write:

console.time("timer");
for (let x=5000; x > 0; x--) {}
console.timeEnd("timer");

The argument of both methods is the timer name. It’s used to identify when to start or end the timer.

Learn New Stuff

New JavaScript features come out every year.

They’re often useful features that we want to use.

So we should read often to keep up with them.

We can go to the MDN website to read about them.

Self-Executing Functions

We can make functions that run automatically when the page loads by wrapping functions with parentheses and then calling them.

For example, we can write:

(() => {
   return {
      name: 'james',
      lastName: 'smith'
   };
})();

We can create functions to return something.

Also, we can keep private variables inside them.

Raw JavaScript Can Always Be Quicker Than Using a Library

If something is available in plain JavaScript, then we should use that instead.

Browsers optimize the standard JavaScript library for speed.

So instead of using a 3rd party HTTP client, we may want to use the Fetch API.

Instead of using Lodash array methods, we can use built-in array methods.

JSON.Parse

JSON.parse lets us parse JSON strings into JavaScript objects.

We can just use it on a JSON string by writing:

JSON.parse(jsonStr);

where jsonStr is the string.

Remove Language and Type

If we’re including JavaScript scripts, we don’t need to add the language and type attributes.

For instance, instead of writing:

<script type="text/javascript" language="javascript" src="script.js"></script>

We write:

<script src="script.js"></script>

Conclusion

We should keep up with new constructs.

They probably save us time.

Other goodies including self calling functions, simplifying script tags, and many things in the JavaScript standard library.

Categories
JavaScript Best Practices

JavaScript Best Practices for Beginners

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.

Use === Instead of ==

=== doesn’t do data type coercion before doing comparisons.

The rules for automatic type coercion are complex so we’ll run into problems if we rely on it.

Therefore, we should use === instead of == for equality comparisons.

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

Eval is Bad

Never use eval in our JavaScript code.

It lets us run JavaScript code from a string.

This is definitely a security issue and JavaScript engines can’t optimize code in a string, so performance will take a hit.

It’s also impossible to debug code in a string easily.

Don’t Use Some Shorthands

Some shorthands are confusing, like omitting the braces for single line blocks.

For instance, we may have things like:

if (foo)
   x = false
   bar();

We may assume that both lines are part of the if block.

But only the first line is part of the block.

Therefore, we should use curly braces to delimit the blocks:

if (foo) {
   x = false;
   bar();
}

Just put them in and we’ll always be clear.

Utilize ESLint

We should use ESLint to find problems in our code and make styles consistent.

This way, we won’t have problems with inconsistency.

Also, it has built-in support for checking Node.js code.

It can also insecure code, TypeScript, JSX, and more with plugins.

Place Scripts at the Bottom of Our Page

We should put scripts at the bottom of the page so that they load after the page content has loaded.

This will make things should up faster for the user.

For instance, we write:

...
  <p>hello world</p>
  <script src="/file.js"></script>
  <script src="/anotherFile.js"></script>
</body>
</html>

to make the scripts load last.

Declare Variables Outside of the For Statement

In a for loop, we can declare variables outside of the for statement so that they aren’t declared every iteration.

For example, instead of writing:

for (let i = 0; i < someArray.length; i++) {
   let container = document.getElementById('container');
   container.innerHtml += `item ${i}`;
   console.log(i);
}

We write:

let container = document.getElementById('container');
for (let i = 0; i < someArray.length; i++) {
   container.innerHtml += `item ${i}`;
   console.log(i);
}

We move the definition of the container variable outside so that we aren’t declaring them at every iteration.

The Fastest Way to Build a String

We can build a string from a bunch of strings faster and shorter with the array instance’s join method.

For instance, we can write:

const arr = ['item 1', 'item 2', 'item 3'];
const arr.join(', ');

to combine strings together with a comma as the separator.

Reduce Globals

We shouldn’t use global variables.

They can easily be overwritten by anything.

For example, instead of writing;

var name = 'james';
var lastName = 'smith';

function doSomething() {...}

We write:

const person = {
   name: 'james',
   lastName: 'smith',
   doSomething() {...}
}

to put the items in an object.

Comment Our Code

We can put comments on our code if they don’t duplicate the code.

It’s also handy for things that we may forget.

Embrace Progressive Enhancement

Ideally, our degrades gracefully even if the user’s browser doesn’t have JavaScript enabled.

We can put a noscript tag in our HTML code to display something if JavaScript is disabled by the user.

If JavaScript is enabled, then we can display the regular content.

Don’t Pass a String to “setInterval” or “setTimeOut”

We shouldn’t pass strings into setInterval or setTimeout .

Running strings are slower since they can’t be optimized.

Also, they pose a security risk since we can pass in anything and try to run it.

And it’s very hard to debug strings.

So instead of writing:

setInterval(
"document.getElementById('container').innerHTML += `number: ${i}`", 3000
);

We write:

setInterval(() => {
  document.getElementById('container').innerHTML += `number: ${i}`
}, 3000);

Don’t Use the “With” Statement

Never use the with statement.

It’s supposed to be a shorthand to access deeply nested objects.

However, the scope is confusing.

So instead of writing:

with (person.has.bodyparts) {
  arms = true;
  legs = true;
}

We write:

person.has.bodyparts.arms = true;
person.has.bodyparts.legs= true;

with is also disabled in strict mode, so we definitely can’t use it in most places.

We can also write:

let o = person.has.bodyparts;
o.arms = true;
o.legs = true;

Conclusion

We shouldn’t use old constructs like with and passing strings into setTimeout or setInterval .

Also, we should compare things with === and !== .

Global variables should also be avoided.