Categories
Javascript

10 JavaScript Tricks that will blow your mind

These programming tricks will help you write readable and concise code. Let’s discuss some of the JavaScript tricks one by one.

In every sphere of life, there exists, a multitude of possibilities that in essence are just different ways to achieve a certain goal. While it rarely matters which way we choose to successfully achieve our goal; it still has it’s own perks, to just be loaded with that knowledge at your disposal. Through this article we aim to highlight some of the most useful of all the programming tricks available in JavaScript.

The programming tricks that we are going to discuss today will not only help you write more readable and concise code but it will also provide you that extra ammunition that sometimes will just make your life easy.

Let’s discuss these JavaScript tricks one by one in brief.

1. Assigning values to multiple variables

A lot of times we end up assigning values to so many variables that it becomes difficult to contain them in few lines. It not only impacts the readability of our code but also makes it difficult to manage the code as we move forward in the longer run. JavaScript gives us an approach to write this code in a single line using something that is famously known as array destructuring. Using array destructuring, we can very easily assign values to multiple variables in a single line.

//Longhand 
let a, b, c; 
a = 5; 
b = 8; 
c = 12;
 
//Shorthand 
let [a, b, c] = [5, 8, 12];

2. Assigning default value

It is very common for a coder to end up in situations where he/she needs to assign some default value to a variable if certain conditions are not met. While most of the language provides a work around for this; JavaScript, as well, provides us a unique way to handle this problem.

We can simply use OR(||) short circuit evaluation to assign a default value to a variable in case the expected value is found empty.

//Longhand 
let imagePath; 
let path = getImagePath(); 
if(path !== null && path !== undefined && path !== '') { 
  imagePath = path; 
} else { 
  imagePath = 'default.jpg'; 
} 

//Shorthand 
let imagePath = getImagePath() || 'default.jpg';

3. Swap two variables

Swapping operations are rather common and handled in a very messy way if one is not aware of certain trick that can easily be availed in JavaScript. To swap two variables, most of the times, we resort to use a third variable that temporarily stores the value to be swapped. But, we can very easily swap two variables with array destructuring assignment.

let x = 'Hello', y = 55; 
//Longhand 
const temp = x; 
x = y; 
y = temp; 

//Shorthand 
[x, y] = [y, x];

4. Template Literals

Suppose we had a problem statement where we are required to concatenate multiple string values stored in different variables. Almost all of us would instantly use “+” operator between our string values and respective variables. With ES6 template literals, we can diffuse this situation in a simpler and more concise way.

//Longhand 
console.log('You got a missed call from ' + number + ' at ' + time); 

//Shorthand 
console.log(`You got a missed call from ${number} at ${time}`);

5. Object Property Assignment

In our coding world, the usage of objects is as common and necessary as a smartphone in this era. Most of the times, the objects and the members accessible to that object would determine the code quality at the very initial stage of development. Although objects definition is quite simple and easy to implement. Yet sometimes it becomes a hassle to define all the members and assign them values, in order to achieve a simple task.

For instance, imagine that we need to define multiple properties and assign them values, but we already have the values stored in different variables. Generally, we would require defining the property name as well as the value to be assigned while object initialization.

However, In JavaScript, if the variable name and object property name is same. Then we can just mention variable name in object literals instead of both key(property name) and value. As a result, JavaScript will automatically set the key same as variable name and assign the value as variable value.

let firstname = 'John'; 
let lastname = 'Wick'; 
//Longhand 
let obj = {firstname: firstname, lastname: lastname}; 

//Shorthand 
let obj = {firstname, lastname};

6. String into a Number

JavaScript inherently comes loaded up with some built in methods like parseInt() and parseFloat() that can easily convert a string to number. However, there still exists another way to perform the same task in a much simpler fashion. That is, to use a unary operator (+) in front of a string value.

//Longhand 
let total = parseInt('453'); 
let average = parseFloat('42.6'); 

//Shorthand 
let total = +'453'; 
let average = +'42.6';

7. Repeat a string for multiple times

Every now and then we are required to perform different operations on strings. And it doesn’t get easier with time as there are endless type of calculations and each requires a unique approach. One such operation is to repeat the string value “n” number of times.

No doubt, using a for loop would be the most easy way that comes to our mind. But JavaScript gives us a much better alternative in the form of a function repeat(). So, to repeat a string for a specified number of times, you can simply use the repeat() method and reduce your code to a single line.

//Longhand 
let str = ''; 
for(let i = 0; i < 5; i ++) { 
  str += 'Hello '; 
} 
console.log(str); // Hello Hello Hello Hello Hello 

// Shorthand 
'Hello '.repeat(5);

8. Merging of arrays

Most of us are aware of the concat() function as it is the most common approach when we are asked to merge multiple arrays. But with ES6 another operator came to the fore. Spread () operator.

Spread operator works like a charm and makes your code look a lot more concise. Let’s look at the illustration below.

let arr1 = [20, 30]; 
//Longhand 
let arr2 = arr1.concat([60, 80]); 
// [20, 30, 60, 80] 

//Shorthand 
let arr2 = [...arr1, 60, 80]; 
// [20, 30, 60, 80]

9. Deep Cloning of multi level object

Cloning is quite self-explanatory as the name suggests it’s usage which is to create the exact copy of an object. There are instances when it becomes necessary to deep clone a multi-level object. To that end, we can iterate through each property and check if the current property contains an object. And if yes, then perform a recursive call to the same function by passing the current property value (i.e. the nested object).

More importantly, we can achieve the same objective by using JSON.stringify() and JSON.parse() that too in a single line.

let obj = {x: 20, y: {z: 30}}; 

//Longhand 
const makeDeepClone = (obj) => { 
  let newObject = {}; 
  Object.keys(obj).map(key => { 
    if(typeof obj[key] === 'object'){ 
      newObject[key] = makeDeepClone(obj[key]); 
    } else { 
      newObject[key] = obj[key]; 
    } 
  }); 
 return newObject; 
} 
const cloneObj = makeDeepClone(obj); 

//Shorthand 
const cloneObj = JSON.parse(JSON.stringify(obj));

10. Find max and min number in array

As our last topic, let’s consider the most common operation of all.

Finding the maximum and minimum of an array of numbers. Using Math.max() and Math.min() functions while passing the array with spread operator, we can perform this task it in a single line.

// Shorthand 
const arr = [2, 8, 15, 4]; 
Math.max(...arr); // 15 
Math.min(...arr); // 2

I hope you have enjoyed reading the article.

Good Luck, Happy Coding.

Let the author know what's in your mind !!

This site uses Akismet to reduce spam. Learn how your comment data is processed.