Extremely useful hacks for JavaScript

Source: Internet
Author: User

In this post I'll share extremely useful hacks for JavaScript. These hacks reduce the code and would help you to run optimized code. So let ' s start hacking!

1) converting to Boolean using !!operator

Sometimes we need to check if some variable exists or if it had a valid value, to consider them as true value. For does this kind of validation, you can use the The !! (Double negation operator) a simple !!variable , which'll autom Atically Convert any kind of the data to the Boolean and this variable would return false if it has some of these values: , null , "" , undefined or NaN , otherwise it'll return true . To understand it in practice, take a look this simple example:

In this case, if a account.cash value is greater than zero, the would be account.hasMoney true.

functionAccount (Cash) { This. Cash =cash;  This. Hasmoney =!!Cash;}varAccount =NewAccount (100.50); Console.log (Account.cash); //100.50Console.log (Account.hasmoney);//truevarEmptyaccount =NewAccount (0); Console.log (Emptyaccount.cash); //0Console.log (Emptyaccount.hasmoney);//false
2) converting to number using +operator

This magic is awesome! And it's very simple-to-be-do, but it's only works with string numbers, otherwise it'll return NaN (not a number) /c7>. There is a look in this example:

function Tonumber (strnumber) {    return +Strnumber;} Console.log (Tonumber (//  1234//  NaN

This magic would work Date with too and, the it would return the timestamp number:

Console.log (+new//  1461288164385
3) short-circuits conditionals

If you see a similar code:

if (conected) {    login ();}

You can shorten it by using the combination of a variable (which'll be verified) and a function using the && (and Oper Ator) between both. For example, the previous code can become smaller on one line:

conected && Login ();

You can do the same-check if some attribute or function exists in the object. Similar to the below code:

User && user.login ();
4) Default values using ||operator

Today in ES6 There is the default argument feature. In order to simulate this feature-browsers you can use the || (OR operator) by including the default value as a Second parameter to be used. If The first parameter returns the second one would be false used as a default value. See this example:

functionUser (name, age) { This. Name = Name | | "Oliver Queen";  This. Age = Age | | 27;}varUser1 =NewUser (); Console.log (user1.name);//Oliver QueenConsole.log (User1.age);// -varUser2 =NewUser ("Barry Allen", 25); Console.log (User2.name); //Barry AllenConsole.log (User2.age);// -
5) Caching the array.lengthIn the Loop

This tip was very simple and causes a huge impact on the performance when processing large arrays during a loop. Basically, almost everybody writes this synchronous to for iterate an array:

 for (var i = 0; i < array.length; i++) {    console.log (array[i]);}

If you work with smaller arrays–it ' s fine, and if you process large arrays, this code would recalculate the size of array In every iteration of this loop and this is cause a bit of delays. To avoid it, you can cache the array.length "a" variable to use it instead of invoking the array.length every time during the loop:

var length = array.length;  for (var i = 0; i < length; i++) {    console.log (array[i]);}

To make it smaller, just write this code:

 for (var i = 0, length = array.length; i < length; i++) {    console.log (array[i]);}
6) Detecting properties in an object

This trick was very useful when you need to check if some attribute exists and it avoids running undefined functions or att Ributes. If you is planning to write Cross-browser code, probably you'll use the this technique too. For example, let's imagine that's need to write code that's compatible with the old Internet Explorer 6 and your want to Use document.querySelector() the-to-get some elements by their IDs. However, in this browser this function doesn ' t exist, so-to-check the existence of this function you can use the in ope Rator, see this example:

if inch document) {    Document.queryselector ("#id"else  {    document.getElementById ("id");}

If there is no querySelector function in document the object and we can use the as document.getElementById() fallback.

7) Getting The last item in the array

The have the power to cut arrays when you set the and Array.prototype.slice(begin, end) begin end arguments. If you don't set end the argument, this function would automatically set the max value for the array. I think that few people know the This function can accept negative values, and if you set a negative number as begin Argu ment you'll get the last elements from the array:

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

This technique can lock the array's size, this is very useful to delete some elements of the array based on the number of Elements want to set. For example, if you have a array with ten elements, but you want to get only the first five elements, you can truncate the Array, making it smaller by setting the array.length = 5 . See this example:

var array = [1,2,3,4,5,6//  6array.length = 3//  3//  [A]
9) Replace All

String.replace()the function allows using String and Regex to replace strings, natively this function is only replaces the first Occurr ence. But can simulate a function by using the at the replaceAll() /g end of a Regex:

var string = "John John"; Console.log (String.Replace (//  "Joana John"// "Joana Joana"
Ten) merging arrays

If you need to merge and arrays you can use the Array.concat() function:

var = [Array1]; var array2 = [4,5,6//  [1,2,3,4,5,6];

However, this function isn't the most suitable to merge large arrays because it'll consume a lot of memory by creating A new array. In this case, you can use Array.push.apply(arr1, arr2) which instead creates a new array–it would merge the second array in the first one Reduci ng the Memory usage:

var = [Array1]; var array2 = [4,5,6//  [1,2,3,4,5,6];
One) converting NodeList to Arrays

If you run document.querySelectorAll("p") the function, it'll probably return an array of DOM elements, the NodeList object. But the This object doesn ' t has all the array ' s functions, like:,,, sort() reduce() map() filter() . In order to enable these and many other native array ' s functions you need to convert NodeList into Arrays. To run the technique just use this function: [].slice.call(elements) :

var // NodeList var // Now the NodeList are an array var // This is another the converting NodeList to Array
Shuffling Array ' s elements

To shuffle the array ' s elements without using any external library like Lodash, just run this magic trick:

var list = [];console.log (List.sort) (function//  [2,1,3]
Conclusion

Now you learned some useful JS hacks which is largely used to minify JavaScript code and some of these tricks is used in Many popular JS frameworks like Lodash, Underscore.js, Strings.js, among others. If you want to go even deeper and learn more about what can minify your code even more and even protect it from prying Eyes talk to us. I hope you enjoyed this post and if you know other JS hacks, please leave your comment on this post!

This entry is posted in JavaScript, tutorials and tagged hacks, javascript by Caio Ribeiro Pereira. Bookmark the permalink.

Extremely useful hacks for JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.