9 Quick JavaScript Tips to Improve Your Code Pt1

9 Quick JavaScript tips to improve your code Pt1

Table of Contents

JavaScript can be sometimes hard to use in the right way. It is language with a couple of quirks and pitfalls. In this article, you will learn about first five JavaScript tips to improve your code. You will explore topics such as strict-mode and debugging and what’s the difference between undefined and null. Then, you will learn about how to simplify if statements. It is still not enough? Well, have you checked out the ES6 syntax? If not, you will have a chance to learn about arrow functions. Lastly, you will see that not all things are truly equal. Let’s learn about some cool JavaScript tips!

No.6-9 are in part 2.

No.1: Use strict-mode

The first item on the list of JavaScript tips we are going to discuss today is about using JavaScript’s strict-mode. Why? The simplest answer is that strict-mode JavaScript will make it easier for you to write safer JavaScript. In the default setting, JavaScript will allow you write “bad syntax“. For example, it will allow you to declare new variables without the keyword var, let or const. When you declare new variable in this way, JavaScript will create it as global variable.

If you are new to JavaScript, global variable is accessible for any function from anywhere. It is variable declared in global scope. Why is it bad to create global variable? The first reason is that they clutter up the global namespace. Second reason is that they are slower than local variables. Third reason is that you can accidentally re-declare it. In other words, you can accidentally rewrite it (change its value). This is just one thing you can do outside the strict-mode.

Strict-mode JavaScript will also not allow you to assign variable to NaN. Outside the strict-mode, when you can try to assign variable to NaN, it will do nothing. What’s worse, you will not get any feedback. You may believe that your code will work while, in a reality, it will not. Another thing strict-mode will not allow you is to use duplicate properties in object literal. Every property in object literal has to be unique. Otherwise, it will throw an error.

The same thing is true for functions. In strict-mode, you can’t use the same name for two function parameters. There are many things not allowed. However, I don’t want to bother you with all of them. Still, if you are curious and want to check them out, MDN is a great place to start.

Why is strict-mode on the top of JavaScript tips list?

What was the reason why I chose Strict-mode to be the leader of this JavaScript tips list? First, I use this directive in every project. Therefore, it is one of the things that come out almost automatically. Second, strict-mode will help you do a better work. In web development, better work means writing flawless and cleaner code. When you work in strict-mode, you can automatically check your code and work for mistakes.

In strict-mode, every bug or example of bad syntax will be turned into JavaScript error. You can then examine all the errors in console and trace them back to their roots. This will make debugging your code much easier and faster.

Two side of implementing strict-mode

There is one thing I want to warn you about. Strict-mode is great for new projects. If you just started working on something, implementing strict-mode takes less than five seconds. You just have to write the directive. Some problems may arise when you decide to implement strict-mode into older projects. Based on my experience, this can be sometimes quite challenging. This will depend on the size of the project and experience of the people working on it. In the worst-case scenario, you may end up with console full of errors and code that doesn’t work.

If this happens, I would suggest following similar approach we discussed in article dedicated to CSS refactoring. This means a couple of things. First, you have to prepare yourself mentally. Second, you should back up all data. Third, divide the code into smaller and more manageable chunks. Finally, have a lot of patience.

Another problem can be if you workflow includes concatenating multiple JavaScript files into one big file. First, it may cause all files to execute in strict mode. If some of your JavaScript files are not in “proper” shape, strict-mode may break something. The same is true if you are using other JavaScript libraries or plugins. Sure, the majority of libraries and plugins are using clean syntax. Many libraries and plugins also sometimes work in strict-mode. However, you can still find plugins that can have some issues with it.

For this reason, I would suggest testing your JavaScript separately first. When you know that everything works great, you can implement external plugins. I would also suggest implementing only one plugin at the time. If you use a lot of them, and implement them all at once, you may end up in chaos. Then, finding the malfunctioning plugin can be quite hard.

No.2: Understand undefined and null

Strict-mode is behind us, so we can take a look at the second item on the JavaScript tips list. In JavaScript, there are two terms some developers think about in the wrong way. These terms are undefined and null. Let’s take a look at the difference between these two. In JavaScript, when something is undefined it can mean one of two things. First, the variable you are referring to has not been declared yet. Second, the variable has been declared, but at this moment it has no value.

When something is null, it is an assignment value that literally means “no value”. You can use it to declare variable that has no value, yet. In terms of natural behavior, JavaScript sets unassigned variables with a default value of undefined. Unless you force it to do it, JavaScript will not set value to null by itself. So, if you find this value somewhere in the code, you know that it was done by human, not computer. Possible way to use at least one of the JavaScript tips as a human detector.

Another difference between undefined and null is that the first is a type (undefined) while the second is a special object. Also, you can’t use undefined in JSON. Well, you can, but then it will not be valid code. This is not true for null. You can use null in JSON. On the top of the differences, there are also at least two things undefined and null have in common. First, both are primitives. In JavaScript, you have five primitives – undefined, null, boolean, string and number. Everything else is an object. Second, both are falsy.

No.3: Use shorter if statements

This third item on our list of JavaScript tips is about making your code shorter and more efficient. From time to time, you will work with good old if statements. In many situations, you will need to come up with more difficult structure of if statements to cover all possibilities. For example, let’s say you want to create logic for four, five or more different cases each containing additional actions. Then … You can move to the next item on our JavaScript tips list.

On the other hand, what if you have short and relatively simple if statement? Then, you can simplify this statement by using ternary operator. By doing this, you can reduce multi-line if statement to one line of code. Let’s illustrate this on very simple example. You have two players playing a game. At the end of the game, you want to decide who is the winner by counting their points. Who will score more points is the winner.

The settings for this example will be three variables – playerAScore, playerBScore and result. We will use the first two variables to save the score during the game. At the end of the game, we will change the value of result variable to one of two strings. Which string will we use will be determined by comparing scores of our players.

Example:

// Before
let playerAScore = 30, 
    playerBScore = 15, 
    result;

if (playerAScore > playerBScore) {
  result = “Player A is the winner.”;
} else {
  result = “Player B is the winner.”;
}

console.log(result); // “Player A is the winner.”

As you can see, this snippet of code is quite lengthy. There are five lines with if statement that are not necessary. We can remove these lines if we replace the if statement with simple ternary operator. What’s more, we can use this operator at the moment we are declaring the “result” variable. This will save as one more line.

Example:

// After
let playerAScore = 30,
    playerBScore = 15,
    result = (playerAScore > playerBScore) ? “Player A is the winner.” : “Player B is the winner.”;

console.log(result); // “Player A is the winner.”

If statement and dealing with function parameters

We can use the same approach to remove potential need for if statements inside functions. Let’s say that you have a function that takes at least one parameter. This parameter is not completely necessary. If you ignore or forget it, there is if statement to use some predefined value instead.

Example:

// Before
function multiply(numberA, numberB) {
  if (typeof numberB === ‘undefined’) {
    numberB = 150;
  }

  return numberA * numberB;
}

multiply(15); // 2250

Example:

// After
function multiply(numberA, numberB) {
  numberB = typeof numberB === ‘undefined’ ? 150 : numberB;

  return numberA * numberB;
}

console.log(multiply(15)); // 2250

// After further optimization
function multiply(numberA, numberB) {
  return typeof numberB === ‘undefined’ ? numberA * 150 : numberA * numberB;
}

console.log(multiply(15)); // 2250

Quick note about the example with function we used previously. In ES6, you can use default parameters. So, if you are using ES6 syntax, you don’t have to use if statement or ternary operator at all. This will allow you to write even less code.

Example:

// Default parameter in ES6
function multiply(numberA, numberB = 150) {
  return numberA * numberB;
}

multiply(15); // 2250

No.4: Learn to use arrow functions

Let’s stay with ES6 for a moment and talk about the next item on JavaScript tips list. With ES6 syntax, we have a new handy tool to write fewer lines of code. This tool is called arrow function. What exactly are arrow functions? These functions, sometimes also called “fat arrow functions”, are a shorter syntax for writing JavaScript functions. These functions use “fat arrow” token – =>. If you are familiar with CoffeeScript, you will probably recognize this. What makes arrow functions different from the “old” functions?

First, arrow functions are anonymous. Second, they change function scoping and the way we work with this keyword in functions. Unlike normal functions, arrow functions capture the keyword this from the surrounding context. These are the main benefits of arrow functions, along with making your code more concise.

Arrow functions with parameters

When you use arrow function, you don’t have to write the function keyword. You also don’t have to use the return keyword. This keyword is implemented in the arrow function. Lastly, you don’t have to use curly brackets. One exception is if you will want to use more than one statement. Let’s also add example for functions with one parameter and multiple statements.

ES5 example:

// Function with two parameters
var multiply = function(numberA, numberB = 150) {
  return numberA * numberB;
};

multiply(15,10);// 150

// Function with one parameter
var calcPower = function(number) {
  return number * number;
};

calcPower(3456); // 11943936

// Function with multiple parameters and statements
// let’s use one of the JavaScript tips to make if statement shorter
var calculate = function (x, y, z) {
  var w = x > y ? x - y : y - x;

  return ((x * y) + z) / w;
}

calculate(5, 15, 23); // 9.8

ES6 example:

// Arrow function with two parameters
let multiply = (numberA, numberB = 150) => numberA * numberB;

multiply(15,10);// 150

// Arrow function with one parameter
let calcPower = number => number * number;

calcPower(3456); // 11943936

// Function with multiple parameters and statements
// again, let’s use one of the JavaScript tips to make if statement shorter
let calculate = (x, y, z) => {
  let w = x > y ? x - y : y - x;

  return ((x * y) + z) / w;
}

calculate(5, 15, 23); // 9.8

Or arrow functions without parameters

As you can see, arrow functions are quite powerful and also easy to use. If you want to create arrow function that takes no parameters, just use blank parenthesis.

ES5 Example:

// Function without any parameters
var greeting = function() {
  console.log(“Good morning!”);
}

greeting(); // “Good morning!”

ES6 Example:

let greeting = () => console.log(“Good morning!”);

Arrow functions and this

In the beginning, I mentioned that arrow functions work with this in a different way than good old functions. How to put this simply? Well, arrow functions don’t have their own this value. If this is true, then, how this works in arrow functions? The value of this is always inherited from its environment, or its enclosing scope. In other words, if you declare arrow function inside the normal function, it will inherit its value for this from that normal function. Let’s give you one incredibly simple example to illustrate this. In this example we have one button in HTML.

Example:

let button = document.querySelector('.button');

button.addEventListener('click', function() {
  console.log(this);// [object HTMLButtonElement]
});

button.addEventListener('click', () => {
  console.log(this);// undefined
});

Best practices for arrow functions

Let’s now briefly describe some of the rules of arrow functions to make this list of JavaScript tips more holistic. First, arrow functions with one parameter don’t need to have parenthesis “()” around the parameter. Second, if arrow function has multiple or no parameters, wrap the parameters in parentheses “()”. Third, if arrow function has one statement in its body, feel free to ignore the braces “{}” around the statement. If arrow function has more than one statements in its body, wrap the block in curly braces “{}”.

By the same token, make sure to use the return statement. Otherwise, function will not return any value. Lastly, if arrow function contains only a single object literal in its body, wrap the object in parentheses “()” (result – “({ … : … })”).

When to use arrow functions

The last question we have to ask is, when should we use arrow functions and when not? You should not use arrow functions in the global scope. Remember that arrow don’t have their own value for this. Another situation when arrow functions are not one of the usable JavaScript tips is when you want to work with Object.prototype properties. Another time when not to use arrow functions is object constructors. In this case, classes are better choice. In any other situation, you can use arrow functions.

No.5: Use right equal operators

The last tip of the JavaScript tips we will discuss in this first is about using the right equal operators. There are two equal operators we can use. The first one is “==”, or its opposite “!=”. This is also called loose equality comparison. The second one is “===” and its opposite “!==”. This is known as strict equality comparison. What’s difference between these two operators? When you use the first operator (“==” or “!=”), it will do automatic type conversion if it is needed. For example, it will convert string to number or number to string.

On the other hand, if you use the second operator (“===” or “!==”), no conversion will be done. This operator will compare both, the value and also the type. For this reason, we can also say that the second operator (strict equal, “===” or ”!==”) could be considered faster.

Example:

‘’ == false // true
‘’ === false // false

'136' == 136 // true
'136' === 136 // false

[55] == 55 // true
[55] === 55 // false

‘’ == 0 // true
‘’ === 0 // false

[] == 0 // true
[] === 0 // false

‘’ == [] // true
‘’ === [] // false

Closing thoughts on JavaScript tips

This is all I have for you in this first part of JavaScript tips mini series. Let’s quickly recap the five JavaScript tips we discussed today. First, start using use strick-mode. It will help you debug your code and avoid writing bad syntax. Second, there is a difference between undefined and null. When variable is undefined, it has not been declared yet or it has no value. On the other hand, when something is null, it is a human-made assignment valuethat means “no value”.

Third, you can simplify less complex if statements by using ternary operator. This way, you can squeeze if statement on multiple lines into single line. Fourth, give ES6 a shot and start using at least arrow functions. This useful tool will help you write shorter code by omitting function and return keywords. Arrow functions also work differently with this keyword. Remember that arrow functions don’t have their own value for this. Make sure to use them in the right scope. Lastly, when you need to perform comparison, make sure to use the right operator.

Remember that loose equal operator (“==”) will perform type conversion if it is needed. Strict equals operator will do not conversion at all. It will compare the value as well as the type. Strict equals operator can be also considered faster than loose equals operator. The remaining JavaScript tips will arrive on Friday. I hope I will see you here again.

If you liked this article, please subscribe so you don't miss any future post.

If you'd like to support me and this blog, you can become a patron, or you can buy me a coffee 🙂

By Alex Devero

I'm Founder/CEO of DEVERO Corporation. Entrepreneur, designer, developer. My mission and MTP is to accelerate the development of humankind through technology.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.