TECHY360
Everything You Need To Know About Tech

11 useful JavaScript tips and tricks

0 59

In this article, we will talk about 11 very useful tricks in the JavaScript language. They will help you reduce the amount of code and optimize it. So, let’s begin. 

Convert to Boolean using the operator  !!

Sometimes we need to check whether the value of a variable exists and whether it is valid, so that in these cases we consider them true, that is, equal true. To do this, you can apply to the operator of the variable double negation !!, which automatically changes any type of data on the logical (boolean) and returns falseonly in cases where the variable takes one of the following values: 0null""undefined or NaN. Here is a simple example:

function Account(cash) {
    this.cash = cash;
    this.hasMoney = !!cash;
}
var account = new Account(100.50);
console.log(account.cash); // 100.50
console.log(account.hasMoney); // true
var emptyAccount = new Account(0);
console.log(emptyAccount.cash); // 0
console.log(emptyAccount.hasMoney); // false

If the value is account.cashgreater than zero, it account.hasMoneywill be equal true.

Converting to Number using the + operator

Amazingly simple trick! It works only with strings, and in all other cases returns NaN (Not a Number) . Take a look at an example:

function toNumber(strNumber) {
    return +strNumber;
}
console.log(toNumber("1234")); // 1234
console.log(toNumber("ACB")); // NaN

This magic also works with the Date type, returning a timestamp :

console.log(+new Date()) // 1461288164385

Simplified notation of conditional expressions

Let’s say we have a similar code:

if (connected) {
    login();
}

It can be reduced by placing an operator &&between a variable (whose value is checked) and a function. This is how we can write our code:

connected && login();

Similarly, you can check whether an object has certain attributes and methods:

user && user.login();

This is due to the so-called short logic: if the left operand  &&is equal  false, then the right operand will not even be calculated, because it is already clear that the whole expression is false. And if the function is the right operand, then it will not be called.

Default Values ​​Using the ||

In ES6, it is possible to set a default argument value. In order to reproduce this feature in older browsers, you can use the operator ||by adding the default value as the second parameter. If the first parameter returns false, the second will be used. Here is an example:

Related Posts
1 of 26
function User(name, age) {
    this.name = name || "Oliver Queen";
    this.age = age || 27;
}
var user1 = new User();
console.log(user1.name); // Oliver Queen
console.log(user1.age); // 27
var user2 = new User("Barry Allen", 25);
console.log(user2.name); // Barry Allen
console.log(user2.age); // 25

You can read more about the ES6 standard in our articles:

Recognizing object properties

The technique is very useful when you need to check whether an attribute or method exists. It can also come in handy with cross-browser layout. Imagine that you need to write code compatible with ancient Internet Explorer 6, and you want to use it document.querySelector()to get elements by identifiers. But in IE6, such a function does not exist, so you need to add a check:

if ('querySelector' in document) {
    document.querySelector("#id");
} else {
    document.getElementById("id");
}

In this example, we can use it document.getElementById()as a fallback if there is no function in the document object querySelector.

Getting the last element of an array

Surely you are familiar with the method  Array.prototype.slice(begin, end): with it you can cut a piece from the array, setting its boundaries beginand end. If you do not specify a value end, the function will automatically set the maximum possible value. But few know that this method can also take negative values ​​- if it beginis equal to a negative number, you will get the last elements of the array:

var array = [1,2,3,4,5,6];
console.log(array.slice(-1)); // [6]
console.log(array.slice(-2)); // [5,6]
console.log(array.slice(-3)); // [4,5,6]

Array shortening

This method allows you to fix the size of the array and remove all unnecessary elements. For example, you have an array of 10 elements, and you need only the first 5. In this case, only one simple command: array.length = 5. Here is a good example:

var array = [1,2,3,4,5,6];
console.log(array.length); // 6
array.length = 3;
console.log(array.length); // 3
console.log(array); // [1,2,3]

Replacing all substrings

The method  String.replace() allows replacing substrings using regular expressions, but by default only the first occurrence of a substring is replaced. However, you can fix this by adding /g“regulars” at the end:

var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"

Merge Arrays

If you need to combine two arrays, you can use the method Array.concat():

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

However, it is not suitable for merging large arrays, since it consumes a large amount of memory, creating a new array. In this case, it is better to use Array.push.apply(arr1, arr2)that puts the second array in the first, reducing memory consumption:

var array1 = [1,2,3];
var array2 = [4,5,6];
console.log(array1.push.apply(array1, array2)); // [1,2,3,4,5,6];

Convert NodeList to Array

If you call document.querySelectorAll("p"), you will  surely get an array of DOM elements, an object of class NodeList. The problem is that it does not have such useful techniques such as sort()reduce()map()and filter(). To activate these and other useful methods, you need to convert the NodeList to an array. To do this, just do [].slice.call(elements):

var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // Теперь NodeList — это массив
var arrayElements = Array.from(elements); // Ещё один способ конвертации

Shuffle Array Elements

To shuffle the elements of an array without using third-party libraries like  Lodash, you can perform this technique:

var list = [1,2,3];
console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]

Conclusion

You learned some useful tricks that allow you to reduce JS code. Many of them are used in libraries such as Lodash, Underscore.js, and Strings.js. If you know other tricks, share them, and we will replenish our article.

Comments
Loading...

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More