In this post, I will share 12 very useful JavaScript tips. These tips can help you reduce and optimize your code.
1) Use !! to convert variables to boolean types
Sometimes we need to check if some variables exist, or if it has valid values, so that their values are considered true. For such checks, you can use || (double negative operator), which automatically converts any type of data into a boolean value, only these variables will return false: 0, null, "", undefined or NaN, and all others will return true. Let's take a look at this simple example:
function Account(cash) { = cash; = !!cash; } var account = new Account(100.50); (); // 100.50 (); // true var emptyAccount = new Account(0); (); // 0 (); // false
In this example, if the value is greater than zero, the value is true.
2) Use + to convert variables into numbers
This conversion is super simple, but it only works on numeric strings, otherwise NaN will be returned (not a number). Take a look at this example:
function toNumber(strNumber) { return +strNumber; } (toNumber("1234")); // 1234 (toNumber("ACB")); // NaN
This conversion operation can also be applied to Date, in which case it will return the timestamp:
(+new Date()) // 1461288164385
3) Short circuit conditions
If you've seen code like this:
if (conected) { login(); }
Then you can use && (AND operator) between these two variables to shorten the code. For example, the previous code can be reduced to one line:
conected && login();
You can also use this method to check whether there are certain properties or functions in the object. Similar to the following code:
user && ();
4) Use || to set the default value
There is a default parameter function in ES6. To emulate this feature in older browsers, you can use || (OR operator) and use the default value as its second parameter. If the first parameter returns false, the second parameter will be returned as the default value. Take a look at this example:
function User(name, age) { = name || "Oliver Queen"; = age || 27; } var user1 = new User(); (); // Oliver Queen (); // 27 var user2 = new User("Barry Allen", 25); (); // Barry Allen (); // 25
5) Cache in loop
This trick is very simple and can avoid a huge performance impact when looping through large arrays. Basically almost everyone uses for to loop through an array like this:
for (var i = 0; i < ; i++) { (array[i]); }
If you use smaller arrays, that's fine, but if you work with large arrays, this code will repeatedly calculate the size of the array in each loop, which will create a certain delay. To avoid this, you can cache in variables so that you can use cache every time in the loop instead:
var length = ; for (var i = 0; i < length; i++) { (array[i]); }
To be more concise, you can write this:
for (var i = 0, length = ; i < length; i++) { (array[i]); }
6) Detect properties in the object
This trick is very useful when you need to check if certain properties exist and avoid running undefined functions or properties. If you plan to write cross-browser code, you may also use this technique. For example, let's assume you need to write code that is compatible with older versions of Internet Explorer 6 and want to use() to get some elements by ID. However, in modern browsers, this function does not exist. So, to check if this function exists, you can use the in operator. Take a look at this example:
if ('querySelector' in document) { ("#id"); } else { ("id"); }
In this case, if there is no querySelector function in the document, it will use() as a substitute.
7) Get the last element of the array
(begin, end) can be used to crop arrays. However, if the value of the end parameter end is not set, the function will automatically set end to the array length value. I think few people know that this function can accept negative values, and if you set a negative number to begin, you can get the inverse element from the array:
var array = [1, 2, 3, 4, 5, 6]; ((-1)); // [6] ((-2)); // [5,6] ((-3)); // [4,5,6]
8) Array truncation
This technique can lock the size of an array, which is very useful for deleting a fixed number of elements in the array. For example, if you have an array with 10 elements, but you want to get only the first five elements, you can stage the array by setting = 5. Take a look at this example:
var array = [1, 2, 3, 4, 5, 6]; (); // 6 = 3; (); // 3 (array); // [1,2,3]
9) Replace all
The () function allows String and Regex to replace strings, and this function itself can only replace the first matching string. But you can add /g at the end of the regular expression to simulate the replaceAll() function:
var string = "john john"; ((/hn/, "ana")); // "joana john" ((/hn/g, "ana")); // "joana joana"
10) Merge arrays
If you need to merge two arrays, you can use the() function:
var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; ((array2)); // [1,2,3,4,5,6];
However, this function is not suitable for large arrays, because it will create a new array and consume a lot of memory. In this case you can use (arr1, arr2), which does not create a new array, but combines the second array into the first array to reduce memory usage:
var array1 = [1, 2, 3]; var array2 = [4, 5, 6]; ((array1, array2)); // [1,2,3,4,5,6];
11) Convert NodeList to an array
If you run the ("p") function, it returns an array of DOM elements, i.e. NodeList object. However, this object does not have some functions belonging to an array, such as sort(), reduce(), map(), filter(). To enable these functions, as well as other native functions of the array, you need to convert the NodeList to an array. To do the conversion, just use this function: [].(elements):
var elements = ("p"); // NodeList var arrayElements = [].(elements); // It has now been converted to an arrayvar arrayElements = (elements); // BundleNodeListAnother way to convert to an array
12) Shuffle the array elements
If you want to reshuffle the data elements like the external library Lodash, just use this trick:
var list = [1, 2, 3]; ((function() { return () - 0.5 })); // [2,1,3]
in conclusion
Now you have learned some useful JS tips, which are mainly used to reduce the amount of JavaScript code, some of which are used in many popular JS frameworks, such as Lodash, etc. If you know other JS tips, please share it!