Lift Up Your Skills with 13 Simple Yet Powerful JavaScript Tricks8 min read

Just like many other languages, JavaScript has plenty of tips and tricks that let you accomplish either simple tasks or difficult tasks succinctly. There are a lot of tutorials about JavaScript tricks that you can easily find on the internet. However, in this article, I want to sum up some of the tricks that I think personally the most useful and handy that you can start using today. Let’s jump in!

Convert Array Element Types

In order to convert the type of the elements in the array, there are a few ways to do it, and traditionally with the help of a for loop:

var convertToString = [1, 2, 3, 4, 5];
for (let i = 0; i < convertToString.length; i++) {
    convertToString[i] = String(convertToString[i]);
}
console.log(convertToString); // [ '1', '2', '3', '4', '5' ]

With the appearance of some handy array methods in JavaScript such as map(), now you can easily convert the type of array element just in a few lines of code:

// converts element type of number to string
var strArr = [1, 2, 3, 4, 5].map(String);
console.log(strArr);

// converts element type of string to number
var numArr = ['1', '2', '3', '4', '5'].map(Number);
console.log(numArr); // [1, 2, 3, 4, 5]

Flip-flopping – Swapping values

Sometimes we all need to swap values of two variables. Typically in many other programming languages, you usually need to store one value to a temporary variable for the swapping process. However, with the introduction of destructuring assignment in ES6, now swapping values can be done neatly:

var a = 5;
var b = 7;
[a, b] = [b, a];
console.log(a); // 7
console.log(b); // 5

Get Unique Values of an Array

How do you usually get the unique values in an array? Might be we usually do this way:

var x = [1, 2, 2, 3, 5, 7, 7, 7];
var newArr = [];
for (let i = 0; i < x.length; i++) {
    if (newArr.indexOf(x[i]) == -1) {
        newArr.push(x[i]);
    }
}
console.log(newArr); // [ 1, 2, 3, 5, 7 ]

But in JavaScript, we already have the built-in Set data structure, which lets us store unique elements of any type, mixing with the rest operator, now get the unique values is never been easier:

var o = [1, 2, 3, 3, 4, 4, 4, 5, 6, 7, 7, 7];
var uniqueArr = [...new Set(o)];
console.log(uniqueArr); // [1, 2, 3, 4, 5, 6, 7]

Short-circuit evaluation

Just like C, Java or many others, JavaScript supports short-circuit evaluating. Besides two boolean values true and false, values in JavaScript can be treated either as truthy or falsy. Those falsy values are null, false, 0 undefined, NaN, and “” (empty) string, all the others are treated as truthy.

With the “&&” (AND operator) if the first value is evaluated to false, then it doesn’t care about the right operand and false will be returned. With the “||” (OR operator) if the left operand is truthy and it will not bother the right operand and return true.

Using the “&&” operator will return the first falsy value, if all values are labeled as truthy then the last value will be return:

// returns the first falsy value
var foo = true;
var bar = 2;
var baz = "abc";
var k = null;
console.log(foo && bar && baz && k); // null

// returns the last truthy value
var a = 1; 
var b = 2;
var c = 3;
var d = 4;
console.log(a && b && c && d); // 4

It’s perhaps a quite different with the “||” operator, it will return the first true value, and if all value is marked as falsy then it will take the last one:

var foo = 1;
var bar = 2;
var baz = 3;
console.log(foo || bar || baz); // 1

var x = undefined;
var y = "";
var z = false;
var w = 0;
console.log(x || y || z || w); // 0

With short-circuiting evaluation, your code can look much shorter, instead of writing this:

if(isThisTrue){
    doSomething();
}else{
    doAnotherThing();
}

Do this:

isThisTrue && doSomething() || doAnotherThing();

So if isThisTrue is true then it will call the doSomething() function, but if it’s false in the first place, doAnotherThing() will be called.

Instead of writing this:

if(truthy){
    return doSomething();
}else{
    return "I will not do anything";
}

Write this:

return (truthy && doSomething() || "I will not do anything");

Merge and Flat Arrays

Merging two or more different arrays can be done with concat() method or spread syntax:

/** Using concat */
// with 2 arrays
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
console.log(arr1.concat(arr2)); // [1, 2, 3, 4, 5, 6]

// more than 2 arrays
var arr3 = [1, 2, 3];
var arr4 = [4, 5, 6];
var arr5 = [7, 8, 9];
console.log(arr3.concat(arr4).concat(arr5)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

/** Using spread operator */
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
console.log([...arr1, ...arr2]); // [1, 2, 3, 4, 5, 6]

Flatting two-dimensional arrays can be also done with spread syntax or flat() method:

var arr = [1, [2, 3],
    [4, 5, 6]
];
console.log(arr.flat()); //  [1, 2, 3, 4, 5, 6]
console.log([].concat(...arr)); //  [1, 2, 3, 4, 5, 6]

Convert number to string and vice versa

To convert a number to a string, we simply use the concatenation operator (+) followed by an empty string:

var num = 1 + "";
console.log(typeof num); // string

To convert a string to a number, we prepend the plus sign before the convertible number string value:

var str = +"20";
console.log(typeof str); // number

Merge Objects

The spread operator is really handy for many circumstances, including merging 2 or more objects into a single collective object:

var person = {name: 'Nam Do', anonymousName: "pUpPyBuTtHoLe"};
var attributes = {strength: 'none', weakness: 'many'};
var fav = {editor: 'vs code', browser: 'opera'};
var altogether = {...person, ...attributes, ...fav};
console.log(altogether);
/* { name: 'Nam Do',
  anonymousName: 'pUpPyBuTtHoLe',
  strength: 'none',
  weakness: 'many',
  editor: 'vs code',
  browser: 'opera' }
*/

Truncate an Array

Sometimes we want to retain some elements from the array and remove all the rest, we can use the length property:

// retains the first 3 array element with the length property
var arr = [1, 2, 3, 4, 5, 6, 7];
arr.length = 3;
console.log(arr); // [1, 2, 3]

Otherwise, we can achieve the same thing but more flexible with slice() method:

var arr = [1, 2, 3, 4, 5, 6, 7];
var arr2 = arr.slice(0, 3);
console.log(arr2); // [1, 2, 3];

First, you need to create a variable to store the truncated array because the slice() method doesn’t modify the original array. The first parameter of the slice method will be the start position (inclusive), the second one is the end position (exclusive).

Remove an element at a particular index

It is one of the hottest JavaScript questions on Stack Overflow, to remove an element at a particular index in an array, we can use the combination of indexOf method and splice() method:

var arr = ['charming', 'clever', 'friendly', 'cowardly', 'generous', 'kind'];
var deleteIndex = arr.indexOf('cowardly');
arr.splice(deleteIndex, 1);
console.log(arr); // [ 'charming', 'clever', 'friendly', 'generous', 'kind' ]

The first thing to do is we get the index of the element we want to eliminate, then we pass this index into the splice() method as the first argument, the second argument is the number of elements we want to delete from this index till the end, just want to delete one element so we pass 1 there.

Convert Object to String

Have you ever tried to convert an object to a string and get something like this:

var obj = {
  name: 'myObj'
};
String(obj); // [object Object]

Many of us might already try it, but it isn’t what we expected, it just prints [object Object] but what we want is the actual content of the object. There is the method JSON.stringify() that we can bail on in this situation:

var obj = {
    name: 'myObj'
}
console.log(JSON.stringify(obj)); // {"name":"myObj"}

Replace text on a String

We can use the replace() method to remove the occurrence we want in a given string:

/** Replaces substring with an empty string */
var str = "This is just a regular sTrInG";
str = str.replace("regular", "");
console.log(str); // This is just a  sTrInG

/** Replaces substring with another string */
var str = "This is a regular sTrInG";
str = str.replace("sTrInG", "string");
console.log(str); // This is a regular string

/** Using regular expression and global flag to remove all occurences */
var str = "test test test test test string test";
str = str.replace(/test/g, "");
console.log(str); //     string 

Dynamic Object’s Property Name

Before JavaScript ES6, if you want to create an object property, first you need to create an object literal and then use either bracket notation or dot notation to create a new property. Now with ES6, you can directly use a variable as your object’s property:

var a = 'name';
var obj = {
    [a]: 'Nam Do',
    gender: 'male'
}
console.log(obj); // { name: 'Nam Do', gender: 'male' }

Convert a NodeList to an Array

When working with DOM, the querySelectorAll() method returns an array-like object called a node list. This data structure is referred to as “Array-like” because it somehow looks like an array but it cannot use some array methods such as forEach() or map(). Here are a few simple ways to convert a node list into an array of DOM elements.

We can convert a node list to an array with Array.from() method:

var nodelist = document.querySelectorAll('div');
var arr = Array.from(nodelist);
/* Now we can apply all array methods to our arr variable
arr.map()
arr.slice()
arr.forEach()
...
*/

Alternatively, we can accomplish the same thing with apply() method:

var nodelist = document.querySelectorAll('div');
var arr = Array.apply(null, nodelist);
/* Now we can apply all array methods to our arr variable 
arr.map()
arr.slice()
arr.forEach()
...
*/

Again, we can get the work done with the support of the spread operator:

var nodelist = document.querySelectorAll('div');
var arr = [...nodelist];
/* Now we can apply all array methods to our arr variable 
arr.map()
arr.slice()
arr.forEach()
...
*/
Previous Article
Next Article

Sign up for newsletter

* indicates required

Categories

Archives