Top 10 Javascript tips

Converting to numbers

JavaScript is a loosely typed language, meaning we don’t have to explicitly specify types of variables. JavaScript also freely type-converts values into a type depending on the context of their use. Converting values to numbers, especially strings to numbers, is a common requirement and many methods can be used.

Managing objects

Destructuring is a huge part of ES6 and something you’re probably going to be using often. It allows us to extract data from objects, and assigning the extracted data into variables:

const rectangle = { h: 100, w: 200 };const { h, w } = rectangle;

We can rename the variables if we want to:

const { h: height, w: width} = rectangle;console.log(height); // 100

Another handy thing we could do is to destructure the returned object by a function and pick and choose what values we want to use: So, with destructuring, we can return multiple values from a function by returning an object and choosing the pieces we want to be returned. Removing a property in an immutable way requires a little trick provided by spread’s counterpart, the rest operator, which is written with three dots (…) like spread. However, in this case, we spread the remaining properties into a new object.

const { age:_ , …person } = getPerson();console.log(person); // {firstName: “Max”, lastName: “Best”}

Now the person object holds all properties from the original person object except age.

Swapping two variables

Using what we learned in the last trick makes swapping variables as easy as:

let me = "happy", you = "sad";[me, you] = [you, me];// me = "sad", you = "happy"

The above code creates an array of [you, me] and immediately destructures them into the opposite variables. No need for temp variables anymore!

Setting defaults

We have all seen them. The endless if statements checking if the values have been set. What if I said there was a better way? Well, that’s exactly what I’m saying, default values.

Random number from interval

There are times when we need a random number to be generated within a range. The Math.random() function helps us generate a random number, and then we can transform it to the range we want:

const randomIntFromInterval = (min, max) => Math.floor(Math.random() * (max — min + 1) + min);

There’s another trick baked into this one if you look at how the function is constructed.

Remove array duplicates

The Set object type introduced in ES6 lets you store unique values. Together with the spread operator (…), we can use it to create a new array with only the unique values:

const uniqueArray = [ Set(array)]

We create a Set from an array and because each value in the Set has to be unique we remove all duplicates. We then convert the Set back to a new array using the spread operator.

Dynamic property names

ES6 brought us computed property names that allow property keys of object literals to use expressions. By surrounding the key with brackets [], we can use variables as property keys: This is useful in a situation where you want the key to be created on the fly. We can access the value with bracket notation:

item[type];   // "kiwi"item["fruit"] // "kiwi"

Or with dot notation:

item.fruit; // "kiwi"

Bonus trick

If we want to add a new item to an array without mutation (which we usually want to avoid), we can create a new array using the ES6 spread operator and slice:

Use Numeric Separators

This is one of the most used operators when I have to deal with large numbers. When using a separator (with just an _) in number it looks better than an unseparated number. For example:

let number = 98234567

to ⬇

let number = 98_234_567

And it works for any other numeric base as well:

const binary = 0b1000_0101;
const hex = 0x12_34_56_78;

Few caveats :

  • More than one underscore in a row is not allowed let num= 100__00
  • Can not be used after leading 0 let num= 0_1
  • Not allowed at the end of numeric literals let num= 100_

Always Use Semicolons

The use of semi-colons for line termination is a good practice. You won’t be warned if you forget it, because in most cases it will be inserted by the JavaScript parser but relying on Automatic Semicolon Insertion(ASI) is not encouraged. This is even included in Google’s, Airbnb’s, and jQuery’s Javascript style guides. To know about what could happen if we rely too much on ASI, checkout the 4th issue of my newsletter I shared some months back. In the last section, I have explained it with an example.