Table of Contents
This guide reviews 12 extremely useful tricks for JavaScript programmers and highlights the differences that matter in everyday use. Compare the options below before making a choice.
- 5 free online HTML editing tools that test the best code
- 13 skills needed to become Frontend Developer
- Beginners of computer programming need to focus on what?
- 13 important SQL statements Programmer needs to know
In this article, TipsMake. Com will share 12 extremely useful tricks for JavaScript programmers . These tips helps you reduce the amount of code as well as help the code run better. Invite you to welcome reading!
1. Convert to Boolean Using Operator! !!
Sometimes we need to check if a variable exists or has a valid value, to see them as True values . To determine, you can use(Double negation operator) a simple!!variable, will automatically convert any boolean data type and this variable will returnfalseWhen it has values like:0 ; null ; undefined0 ; null ; undefined0 ; null ; orNaN, otherwise it will returntrue. To better understand how it works, take a look at the following simple example:
function Account(cash) {this.cash = cash;this.hasMoney = !!cash;}var account = new Account(100.50);console.log(account.cash); // 100.50console.log(account.hasMoney); // truevar emptyAccount = new Account(0);console.log(emptyAccount.cash); // 0console.log(emptyAccount.hasMoney); // false
In the above example, if theaccount.cashValue is greater than 0,account.hasMoneyWill have a value of true.
2. Convert to Number Using the + Operator
This procedure is excellent and easy to perform. However, it only works with numeric strings, otherwise it returnsNaN(Not a Number - Not a number). Take a look at the following example:
function toNumber(strNumber) {return +strNumber;}console.log(toNumber("1234")); // 1234console.log(toNumber("ACB")); // NaN
This trick also works for bothDateAnd in this case it returns the timestamp number:
console.log(+new Date()) // 1461288164385
3. Shorten the Conditions
If you see a code like the one below:
if (conected) {login();}
You can shorten it by combining a variable (to be validated) and a function using(AND operator) in the middle. For example, the above code may become more concise in a line:
conected && login();
You can do the same to check if the property or function exists in the object. Similar to the code below:
user && user.login();
4. Set the Default Value Using the |||| Operator
function User(name, age) {this.name = name || "Oliver Queen";this.age = age || 27;}var user1 = new User();console.log(user1.name); // Oliver Queenconsole.log(user1.age); // 27console.log(user1.age); // 27var user2 = new User("Barry Allen", 25);console.log(user2.name); // Barry Allenconsole.log(user2.age); // 25
5. Store Array. Length in the Loop
This trick is very simple and has a great impact on performance when processing large arrays in the loop. Basically, most people use aforLoop to browse the array as follows:
for (var i = 0; i < array.length; i++) {console.log(array[i]);}
It's okay to work with small arrays, but if you handle large arrays, this code will recalculate the size of the array after each iteration and that will cause a bit of delay. To avoid this, you can store the array. Length in a variable to use it instead of callingarray.lengthIn each iteration:
var length = array.length;for (var i = 0; i < length; i++) {console.log(array[i]);}
To make it look more compact, simply rewrite the following:
for (var i = 0, length = array.length; i < length; i++) {console.log(array[i]);}
6. Identify Attributes in an Object
This trick is extremely useful when you need to check if the property exists and avoid running unspecified functions or attributes. If you intend to write code that runs on multiple browsers, you can also use this technique.
For example, imagine you need to write code that is compatible with the old Web browser Internet Explorer 6 - IE6 and you want to usedocument.querySelector()To get some elements by their ID. However, in IE6 this function does not exist. To check if the function exists, use the in Operator as the example below:
if ('querySelector' in document) {document.querySelector("#id");} else {document.getElementById("id");}
In this case, if there is noquerySelectorFunction in the document, we can usedocument.getElementById()Instead.
7. Get the Last Element in the Array
Array.prototype.slice(begin, end)Can cut the array when you set thebeginAndendParameters. But if you do not enter theendParameter, this function will automatically set the maximum value for the array. Surely few people know that this function can accept negative values and if you set thebeginParameter to be a negative number, you will get 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. Short Cut Array
This technique can lock the array size, which is useful when you want to delete some elements of the array based on the number of elements you set. For example, if you have an array of 10 elements but you only want to get the first 5 elements, you can truncate the array, making it smaller by settingarray.length = 5. See the following example:
var array = [1, 2, 3, 4, 5, 6];console.log(array.length); // 6array.length = 3;console.log(array.length); // 3console.log(array); // [1,2,3]
9. Replace the Whole
TheString.replace()Function allows to use String And Regex To replace strings, but this function only replaces the first substring that appears. You can simulate a functionreplaceAll()Using/gAt the end of the Regex:
var string = "john john";console.log(string.replace(/hn/, "ana")); // "joana john"console.log(string.replace(/hn/g, "ana")); // "joana joana"
10. Include the Array
If you need to put two arrays together, you can use theArray.concat()Function:
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 best way to merge large arrays as it will consume a lot of memory by creating a new array. In this case, you can useArray.push.apply(arr1, arr2)Instead of creating a new array, it will merge 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 rundocument.querySelectorAll("p"), it will return an array containing DOM elements, NodeList objects. But this object doesn't have all the functions of the array like:sort() ; reduce() ; map() ; filter()sort() ; reduce() ; map() ; filter()sort() ; reduce() ; map() ; filter(). To be able to use these and many other available functions of the array, you need to convert the NodeList into an array. You only need to use the function:[].slice.call(elements):
var elements = document.querySelectorAll("p"); // NodeListvar arrayElements = [].slice.call(elements); // Now the NodeList is an arrayvar arrayElements = Array.from(elements); // This is another way of converting NodeList to Array
12. Mix Elements in the Array
To tamper with the elements in the array without using separate libraries like Lodash , you only need to use the following trick:
var list = [1, 2, 3];console.log(list.sort(function() {return Math.random() - 0.5})); // [2,1,3]
Conclude
Now you have learned some useful JavaScript tricks that are mostly used to minimize code and some tricks used in popular JavaScript frameworks like Lodash, Underscore. Js, Strings. Js and many frameworks. Other.
Hope you enjoy this article and if you still know any other useful JavaScript tips, let us know in the comment section below!
Refer to some more articles:
- Do you know the 15 hottest programming languages on this GitHub?
- 7 Framework JavaScript for mobile app development
- If you want a successful career, find out about the five 2018 technology trends!
Having fun!
FAQ
How should I compare the options in this list?
Compare compatibility, essential features, ease of use, support, and total cost rather than choosing by popularity alone.
Are free options enough for most users?
Free options may cover basic needs, but advanced features, fewer limitations, and better support can make a paid option worthwhile.
What feature matters most when choosing?
Prioritize the feature that solves your main need reliably on the device or platform you use.
Reader Comments 0
Sign in with email or Google to join the discussion.