10 JavaScript Practices That Will Pimp Your Code!

Simple tips and tricks every JS developer should know

Motivation

Many of my colleagues and I have noticed after a long period of development that JavaScript is full of surprises.
It surprises us again and again and I always learn something new about this programming language.
In this article, I’ll try to introduce some of my favorite practices from the world of JavaScript that you might want to use in your projects.

1. Faster Conditions

When it comes to code, it goes without saying, the shorter the better! Since every application needs conditions like the if statement, we should also learn the abbreviation. The “&&” operator.

const checkThisOne = true;//The long way
if (checkThisOne) {
doSomethingAwesome();
}
//The abbreviation
checkThisOne && doSomethingAwesome();

2. Check Attributes

As developers, we regularly want to make sure that we only access sub-attributes if the upper attribute exists. This creates long chains of checks that complicate the code. With the “?” Operator we can get around this very easily.

// Instead of this
if(data && data.fruit && data.fruit.name === "Apple"){
}
// Do this
if(data?.fruit?.name === "Apple"){
}

3. Empty an Array

Ever wanted to empty an array quickly?
We can easily empty an array by simply assigning the value 0 to the “length” attribute. Easy as that!

const fruits = ["Apple", "Banana", "Kiwi", "Cherry"]
fruits.length = 0;

4. Text formatting

Often texts are created as strings with double or single quotation marks. These have many limitations and create chaos in your code.
Template literals offer a much better alternative. The texts are created with the help of the “backtick symbol” (`). These can then simply be used and referenced in new strings.

const person = "David";
const what = "an apple";
// Without
const sentence = person + " eats " + what + " in the evening."
// With template literals
const sentence= `${person} eats ${what} in the evening.`;

5. Remove duplicates from an array

Since JavaScript is constantly evolving, ES 6 has finally added a “Set”.
By definition, a set is an object that only stores unique values. This means that no element can be repeated in a set.
Perfect for removing duplicate values!
To do this, we first convert our array to a set. This will automatically remove any duplicate values. Finally, we just convert it back to an array.

const fruits = ["Apple", "Banana", "Kiwi", "Cherry", "Apple", "Cherry"]
const fruitsToBuy = […new Set(fruits)];

6. Creating an array

We use arrays all the time, so this tip is especially important.
We can easily create a new or empty array in a single line. How?

// A real headache
const array = new Array();
array[0] = "Apple";
array[1] = "Pie";
// Much better
const array = ["Apple","Pie"];
// Empty works too!
const array = [];

7. Passing array values

I am sure you know this one as well. We want to pass all elements of an array as individual parameters to another function or insert them into another array. Luckily the “Spread” operator helps us to do that!

const fruits = ["Apple", "Banana", "Kiwi", "Cherry"];
const moreFruits = ["Mango", "Pineapple", ...fruits];

8. Copy objects

Boy this one is the source of many errors. In JavaScript, objects are references, so we can’t just clone them with an “=”.

If a variable “fruit” is an object, a memory with an address is allocated for it. Then we create the variable “fruitCopy” and assign it fruit. Since “fruit” is an object, instead of a new address in memory, “fruitCopy” gets simply pointed to the same object with the previously known address.
Because of this, all changes to “fruitCopy” are also transferred to “fruit”, as they refer to the same address.

// JSON Object
const fruit = {name:"Apple",color:"red"};
const fruitCopy = fruit;
fruitCopy.name = "Banana";
// Both are the same
fruit.name === fruitCopy.name => true
// Array
const fruits = ["Apple", "Banana", "Kiwi", "Cherry"];
const fruitsCopy = fruits;
fruitsCopy[0] = "Pineapple";
// Both are the same
fruitsCopy[0] === fruits[0] => true

However, we can do cloning properly in just a single line using the following methods! This way it is a real copy and not a reference.

const fruit = {name:"Apple",color:"red"};// Like so
const fruitCopy = { ...fruit};
// or with Object.assign
const fruitCopy = Object.assign({}, fruit);
// oder using JSON.parse
const fruitCopy = JSON.parse(JSON.stringify(fruit));

9. Check if an object is empty

I am sure you are familiar with checking objects against null. Only to see that it is then empty and does not have any attributes.
That is always annoying! Using Object.entries () we can return an array of the object properties. Then all we have to do, is check the length of this array.

const fruit = {name:"Apple",color:"red"};
const emptyFruit = {};
Object.entries(fruit).length === 0 => false
Object.entries(emptyFruit).length === 0 => true

10. The easy for-loop

The “For-Loop” was the first iterator function that I was allowed to learn in programming. In JavaScript, among other things, String, Array and Map implement the iterator functionality. That means you can iterate over them using “for … of” loops. They are much slimmer.
With “for … of” loops we don’t even need the length or an index variable!

// Classic
const fruits = ["Apple", "Banana", "Kiwi", "Cherry"];let
for(let i = 0; i < fruits.length ; i++) {
console.log(fruits[i]);
}
// Simple and quick
for(fruit of fruits) {
console.log(fruit);
}
// If you need the index
for(index in fruits) {
console.log(fruits[index]);
}
// Or both
for (const [index, fruit] of fruits.entries()) {
console.log(index, fruit);
}

Summary

That’s it now for this post.
Here’s another great book with more tips and tricks:

https://www.amazon.de/Javascript-Definitive-Most-Used-Programming-Language/dp/1491952024/

I hope this article was helpful and you learned something new!

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store