7 Useful JavaScript Tricks and Tips

7 Useful JavaScript Tricks and Tips

You Will Be Surprised By Number 9!

Featured on daily.dev

In this article, I gathered some JavaScript tips and tricks that I believe can make you a better JavaScript developer. In no particular order, here are seven (?) JavaScript tricks!

1. 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.

Unary + operator

The most concise method for type-converting strings into numbers is the unary + operator:

+"42"  // 42

A unary operation is an operation with only one operand. This operand comes either before or after the operator.

The unary plus operator precedes its operand and evaluates to its operand but attempts to convert it into a number if it isn't already. Here are a few more examples of how it behaves:

+true  // 1
+false // 0
+null  // 0

But, what if we want to be more explicit in our code?

Number

Number is a primitive wrapper object used to represent and manipulate numbers. When used as a function, Number(value) converts a string or other value to the Number type. If the value can't be converted, it returns NaN (Not a Number).

Number('42')   // 42
Number('1.3')  // 1.3
Number('tax')  // NaN

parseInt

parseInt() takes a String as a first argument and a base to which that String will be converted to. This method always returns an integer.

parseInt('1234', 10)       // 1234
parseInt('11 players', 10) // 11
parseInt('player 2', 10)   // NaN
parseInt('10.81', 10)      // 10

parseInt() tries to get a number from a string that does not only contain a number, but if the string does not start with a number, you’ll get NaN.

parseFloat

If we want to retain the decimal part and not just the integer part, we can use parseFloat() that takes a String as an argument and returns the Float point number equivalent.

parseFloat('10.42') // 10.42
parseFloat('10.00') // 10

There are a few more ways to convert to numbers but these are the more common ones.

2. 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:

function getPerson() {
  return {
    firstName: 'Max',
    lastName: 'Best',
    age: 42
  }
}

const { age } = getPerson();
console.log(age); // 42

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.

3. 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!

4. 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.

Variables

The nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined and otherwise returns its left-hand side operand. We can use this to set default values, for example when we receive a list that has not been set to an array yet:

const bookList = receivedBooks ?? [];

Parameters

We could use the null coalescing operator to set defaults for variables in functions but there is a better way, default parameters:

function calculateArea(width, height = 100) {
    return width * height;
}

const area = calculateArea(50);
console.log(area); // 5000

Here we set the default value for height to 100 and calculate the area by only sending in the width.

Objects

Another trick when destructruring objects is setting default values:

const rectangle = { height: 400 };
const { height = 750, width = 500 } = rectangle;
console.log(height); // 400 - comes from rectangle object
console.log(width);  // 500 - fallback to default

ES6 destructuring default values only kick in if the value is undefined.

5. 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.

6. 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 = [...new 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.

7. 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:

const type = "fruit";
const item = {
  [type]: "kiwi"
};

console.log(item); // {fruit: "kiwi"}

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"

8. 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.

const insert = (arr, index, newItem) => [
  ...arr.slice(0, index), // first half of array
  newItem,                // new item
  ...arr.slice(index)     // rest of array
];

const items = ['S', 'L', 'C', 'E']

const result = insert(items, 2, 'I');

console.log(result); // ["S", "L", "I", "C", "E"]

9.

Why was 6 afraid of 7?

Because 7 ate 9.

Conclusion

I hope you find some of these JavaScript tricks useful and worth adding to your everyday arsenal. And remember, being responsible is far more important than being efficient.

Did you find this article valuable?

Support Michael Karén's Blog by becoming a sponsor. Any amount is appreciated!