DEV Community

Phantom
Phantom

Posted on

5 JavaScript tips and tricks that are worth using

My first dev video on YouTube and thus my first dev article on dev.to. I appreciate to have the opportunity to share my creativity combined with productive content for web developers. I hope you can get something out of the video/article and you might have tips for me to provide better content.

Introduction

There are thousands of useful JavaScript tips and tricks outside, that probably one day our code only consists of tips and tricks. In this article, I'm going to present you my 5 favorite JS tips and tricks to write more readable, more predictable, and thus much cleaner code to make you an efficient developer.

1.) swap variables with destructuring

You've most probably heard of destructuring in JavaScript and once you understand it, it's an excellent feature of ES2015 you don't want to miss out. Destructuring lets you extract the values inside an array into individual variables by merely declaring your new variables on the left side of the equality operator. The array, you want to get the values out of, sits on the right side. Now, the variable cat is assigned to Danny, dog to Catherine, and turtle to Tommy. But something seems to be wrong here right? What if you made a mistake and you interchanged Danny the dog with Catherine the cat by accident? Well, it turns out that you can easily swap the values. On the left side of the equality operator is the array holding the variable you want to swap. The same on the right side with the difference that you change the positions of the two variables. That's it! Catherine and Danny are now in the right shape.

const myPets = ['Danny', 'Catherine', 'Tommy'];

// ES2015 destructuring
[cat, dog, turtle] = myPets;

// swap vars
[cat, dog] = [dog, cat];

2.) fallback / default value with OR

The logical OR operator analyses at least two values of their truthiness. If one value is falsy the other must be truthy in order to get a boolean value of true. But assume you have an object property that gets its value dynamically from - for example - a parameter of a function. What if the parameter is undefined or even null? You could use default parameters that were introduced in ES6 or use a default value if the first value is nothing but void. In this example, we imagine getting two values from a form: firstname and username. The username is optional and if the user does not provide one, the backend creates an anonymouse one using a default/fallback value by typing the logical OR operator after the parameter followed by the default value. In case 'username' is not defined or not existent the object property takes 'phantomCode' rather than 'undefined 'or 'null'.

function sendForm(firstname, username) {
  const userObj = {
    firstname,
    username: username || 'Phantom',
  }
  return userObj;
  // firstname: 'Tailor'
  // username: 'Phantom'
}

sendForm('Tailor');

3.) Remove duplicates inside an array

An array can hold different data types. Basically, you can create an array-ception and make a tremendous amount of nested arrays. Think of an array that holds hundreds of names with a lot of duplicates. You as a developer would like to diminish the array to only hold unique names. There is a cumbersome way to do it by making use of the Array.prototype.filter method and check if the indexes match. But you can do it with a one-liner by just creating a set. A set has the characteristic to only hold unique values. So what we do is we create a new set out of our existing array by passing it as an argument to the Set constructor function. In order to convert it to an array just wrap the whole function inside the Array.from method. Now you have created an ordered set of data that only contains unique strings.

const myNames = ['Jack', 'Christine', 'Alan', 'Lisa', 'Albert', 'Brandon', 'Tim', 'Lisa', 'Marc', 'Jack', 'Alan'];

// cumbersome solution
const myCumbersomeArray = myNames.filter((currentValue, index) => {
  return myNames.indexOf(currentValue) === index;
});

// most convenient way
Array.from(new Set(myNames));

4.) Spread operator at the beginning

Just three dots can make your life as a web developer so much more relaxed. You know what I am talking about: the spread-operator. It allows you to easily concatenate arrays. But did you know that it matters in which place you put your spread-operation in to from a performance perspective? Well, at least it matters in Google Chrome due to their optimized V8 engine.
Consider this example: the function concatenates two arrays that are passed as arguments. It returns a new array that consists of a string and two arrays. And this is the perfect timing to gain a performance boost by solely moving the spread-operations to the front. By changing the position from the end to the front it gives a performance boost of up to 50 % which you probably won't recognize but it matters if you have larger applications and more complex functions. This is due to the so-called 'fast-path optimization' for spread operations. You can dig into the topic very deep by reading the article by the v8 developers.

const part1 = [1, '+', 1];
const part2 = ['=', 2];

function concateArrays(arr1, arr2) {
  // return ['Simple math ...', ...arr1, ...arr2];
  return [...arr1, ...arr2, 'Simple math ...']; // better
}

concateArrays(part1, part2);

5.) for ... of loop

The next tip is about the for-of-loop. It was created to loop over iterable objects like strings, arrays, maps or even NodeLists. It's a neat alternative to other for-loops because it's concise, predictable and easy to read with one blink.
If you have an array you can just call for and pass in a temporary variable or constant followed by the keyword 'of' and then the array. Inside the block, you now have access to every item inside the iterable like in other for-loops.
Same with strings: just imagine an inspiring person and give that person a for-of-loop. What does he do? Well, he splits his name into separate letters.
Then there are so-called 'array-like'-objects. They can be treated as an array but in fact, they aren't. For example the arguments keyword of a function or a NodeList you gather from the DOM.
And for the sake of clarity here is an example with an object. It's slightly different. You have to make use of the Object.entries() method. Put your object as an argument inside and try to log the data. What you get is an array for every key-value-pair.

const shoppingCart = {
  bananas: 3,
  sweets: 1,
  water: 7,
}

for (const item of Object.entries(shoppingCart)) {
  console.log(item);
}

Summary

Alright, that were 5 useful JavaScript tips and tricks. I hope you've learned something new and you can go ahead to improve your code. If you sight anything wrong just let me know! Thanks for reading.

If you liked the post/video I'd appreciate to see you as a follower on my social media:
YouTube
Twitter
Facebook

Top comments (0)