12 extremely useful tips that every JavaScript programmer should know

1. Convert data type to boolean using operator !!

Sometimes we need to check if some variable exists or if it has a valid value. To confirm such, you can use !!(double negative operator). It will automatically convert all data types of variables boolean and will return falseonly if it has the same value as: 0, null, "", undefinedor NaN, on the contrary it will return true. To understand more about how it works, take a look at this 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

In the example above, if account.cashthe value is greater than 0 then account.hasMoneythe value is true.

2. Convert data type to number using the + operator

This trick is great and easy to do, but it only works with a string of numbers, otherwise it will return NaN(Not a Number). Let’s look at the following example:

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

This trick also works with both Dateand in this case it returns the timestamp:

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


3. Conditional shortening

If you see a code like this:

if (conected) {  

You can reduce it by combining a variable (to be validated) and a function to use &&(the AND operator) in the middle. For example, the above code can become concise in one line:

conected && login();

You can do the same to test if some of the attributes or functions exist in the object. Similar to the code below:

user && user.login();


4. Set the default value using the || operator

Today in ES6 has support for default parameters. In case you want to simulate this feature in older browsers then you can use ||(OR character) by inserting the default value as the second parameter to use. If the first parameter returns false, the second parameter will be used as the default value. See the following example:

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


5. Cache array.length in the loop

This tip is very simple and has a big impact on performance when handling large arrays in a loop. Most people use the following loop forto browse the array:

for (var i = 0; i < array.length; i++) {  

If you work with small arrays, that’s fine, but if you’re dealing with large arrays, this code will recalculate the array size after each iteration and cause some delay. To avoid this, you can cache array.lengthin a variable to use it instead of calling it array.lengthin each iteration:

var length = array.length;  
for (var i = 0; i < length; i++) {  

To make it look neat, just rewrite the following:

for (var i = 0, length = array.length; i < length; i++) {  


6. Identify properties in an object

This trick is extremely useful when you need to test if some attributes exist and it helps to avoid undefined functions or attributes. If you are going to write code that runs on multiple browsers then you can also use this technique. For example, imagine that you need to write code that is compatible with IE6 and that you want to use document.querySelector()to get some elements by their ID. However, in this browser does not exist, so to check whether this function exists you can use the operator in, see for example:

if ('querySelector' in document) {  
} else {

In this case, if there is no querySelectorinner function document, we can use document.getElementById()instead.

7. Get the last element in the array

Array.prototype.slice(begin, end)Can cut the array when you set the parameter beginand end. But if you do not enter a parameter end, this function will automatically set the maximum value for the array. I think few people know that this function can accept negative values, and if you set the parameter to beginbe a negative number then you will retrieve the last element from 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]


8. Truncate the array

This technique can lock the array size, which is very useful for deleting some elements of the array based on the number of elements you want. For example, if you have an array of 10 elements but you just want to get the first 5 elements then you can truncate the array, making it smaller by putting array.length = 5. See the following 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]


9. Replace the whole

The function String.replace()allows the use of String and Regex to replace strings, but this function only replaces the substrings that appear first. But you can simulate a function replaceAll()using the /glast Regex:

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


10. Include arrays

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

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

However, this function is not the most appropriate way to include large arrays because it consumes a lot of memory by creating a new array. In this case, you can use Array.push.apply(arr1, arr2). Instead of creating a new array, it will enclose the second array into the first array, thereby reducing memory usage:

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


11. Convert NodeList to array

If you run the function document.querySelectorAll("p"), it returns an array containing the DOM – NodeList object. But this object does not have the full array of functions such as: sort(), reduce(), map(), filter(). In case you want to use these functions and many other built-in functions of the array, you need to pass the NodeList array. To implement this technique you just use the function:[].slice.call(elements)

var elements = document.querySelectorAll("p"); // NodeList  
var arrayElements = [].slice.call(elements); // Now the NodeList is an array  
var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array


12. Scramble the elements in the array

To tamper with array elements without using private libraries like Lodash, just use the following trick:

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



Now you have learned some useful JavaScript tricks that are mostly used to reduce code and some of the tricks used in popular JS frameworks such as Lodash, Underscore.js, Strings.js, and many frameworks. other. Hope you enjoy this article and if you know any other JS tips, let me know under the comments section!

Leave a Reply