12 Most Useful Tips and Tricks JavaScript you Must Know

Posted on

As you know, JavaScript is the number one programming language in the world, the language of the web, of mobile hybrid apps (like PhoneGap or Appcelerator), of the server side (like NodeJS or Wakanda) and has many other implementations. It’s also the starting point for many new developers to the world of programming, as it can be used to display a simple alert in the web browser but also to control a robot (using nodebot, or nodruino). The developers who master JavaScript and write organized and performant code have become the most sought after in the job market.

In this article, I’ll share 12 hand-picked tips that strike me as particularly clever or useful. This post is intended to be useful for beginners, but I hope even intermediate JavaScript developers will find something new in this list.

1. Filter Unique Values


The Set object type was introduced in ES6, and along with …, the ‘spread’ operator, we can use it to create a new array with only the unique values.

const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];console.log(uniqueArray); // Result: [1, 2, 3, 5]

Before ES6, isolating unique values would involve a lot more code than that!

This trick works for arrays containing primitive types: undefined, null, boolean, string and number . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!)

2. Short-Circuit Evaluation


The ternary operator is a quick way to write simple (and sometimes not-so-simple) conditional statements, like these:

x > 100 ? 'Above 100' : 'Below 100';
x > 100 ? (x > 200 ? 'Above 200' : 'Between 100-200') : 'Below 100';

But sometimes even the ternary operator is more complicated than necessary. Instead, we can use the ‘and’ && and ‘or’ || logical operators to evaluate certain expressions in an even more concise way. This is often called ‘short-circuiting’ or ‘short-circuit evaluation’.


Leave a Reply

Your email address will not be published. Required fields are marked *