{"id":8562,"date":"2017-04-04T07:48:00","date_gmt":"2017-04-04T07:48:00","guid":{"rendered":"http:\/\/graphenelive.in\/?p=607"},"modified":"2017-04-04T07:48:00","modified_gmt":"2017-04-04T07:48:00","slug":"12-extremely-useful-tips-every-javascript-programmer-know","status":"publish","type":"post","link":"http:\/\/graphenelive.in\/12-extremely-useful-tips-every-javascript-programmer-know\/","title":{"rendered":"12 extremely useful tips that every JavaScript programmer should know"},"content":{"rendered":"

1. Convert data type to boolean using operator !!<\/h3>\n
\nSometimes we need to check if some variable exists or if it has a valid value. To confirm such, you can use !!<\/code>(double negative operator). It will automatically convert all data types of variables boolean and will return false<\/code>only if it has the same value as: 0<\/code>, null<\/code>, \"\"<\/code>, undefined<\/code>or NaN<\/code>, on the contrary it will return true<\/code>. To understand more about how it works, take a look at this simple example:<\/p>\n<\/div>\n
function Account(cash) {  \n    this.cash = cash;\n    this.hasMoney = !!cash;\n}\nvar account = new Account(100.50);  \nconsole.log(account.cash); \/\/ 100.50  \nconsole.log(account.hasMoney); \/\/ true\nvar emptyAccount = new Account(0);  \nconsole.log(emptyAccount.cash); \/\/ 0  \nconsole.log(emptyAccount.hasMoney); \/\/ false<\/code><\/pre>\n

In the example above, if account.cash<\/code>the value is greater than 0 then account.hasMoney<\/code>the value is true<\/code>.<\/p>\n

2. Convert data type to number using the + operator<\/h3>\n

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

function toNumber(strNumber) {  \n    return +strNumber;\n}\nconsole.log(toNumber(\"1234\")); \/\/ 1234  \nconsole.log(toNumber(\"ACB\")); \/\/ NaN<\/code><\/pre>\n

This trick also works with both Date<\/code>and in this case it returns the timestamp:<\/p>\n

console.log(+new Date()) \/\/ 1461288164385<\/code><\/pre>\n

 <\/p>\n

3. Conditional shortening<\/h3>\n

If you see a code like this:<\/p>\n

if (conected) {  \n    login();\n}<\/code><\/pre>\n

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

conected && login();<\/code><\/pre>\n

You can do the same to test if some of the attributes or functions exist in the object. Similar to the code below:<\/p>\n

user && user.login();<\/code><\/pre>\n

 <\/p>\n

4. Set the default value using the || operator<\/h3>\n

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

function User(name, age) {  \n    this.name = name || \"Oliver Queen\";\n    this.age = age || 27;\n}\nvar user1 = new User();  \nconsole.log(user1.name); \/\/ Oliver Queen  \nconsole.log(user1.age); \/\/ 27\nvar user2 = new User(\"Barry Allen\", 25);  \nconsole.log(user2.name); \/\/ Barry Allen  \nconsole.log(user2.age); \/\/ 25<\/code><\/pre>\n

 <\/p>\n

5. Cache array.length in the loop<\/h3>\n

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 for<\/code>to browse the array:<\/p>\n

for (var i = 0; i < array.length; i++) {  \n    console.log(array[i]);\n}<\/code><\/pre>\n

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.length<\/code>in a variable to use it instead of calling it array.length<\/code>in each iteration:<\/p>\n

var length = array.length;  \nfor (var i = 0; i < length; i++) {  \n    console.log(array[i]);\n}<\/code><\/pre>\n

To make it look neat, just rewrite the following:<\/p>\n

for (var i = 0, length = array.length; i < length; i++) {  \n    console.log(array[i]);\n}<\/code><\/pre>\n

 <\/p>\n

6. Identify properties in an object<\/h3>\n

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()<\/code>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<\/code>, see for example:<\/p>\n

if ('querySelector' in document) {  \n    document.querySelector(\"#id\");\n} else {\n    document.getElementById(\"id\");\n}<\/code><\/pre>\n

In this case, if there is no querySelector<\/code>inner function document<\/code>, we can use document.getElementById()<\/code>instead.<\/p>\n

7. Get the last element in the array<\/h3>\n

Array.prototype.slice(begin, end)<\/code>Can cut the array when you set the parameter begin<\/code>and end<\/code>. But if you do not enter a parameter end<\/code>, 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 begin<\/code>be a negative number then you will retrieve the last element from the array:<\/p>\n

var array = [1, 2, 3, 4, 5, 6];  \nconsole.log(array.slice(-1)); \/\/ [6]  \nconsole.log(array.slice(-2)); \/\/ [5,6]  \nconsole.log(array.slice(-3)); \/\/ [4,5,6]<\/code><\/pre>\n

 <\/p>\n

8. Truncate the array<\/h3>\n

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<\/code>. See the following example:<\/p>\n

var array = [1, 2, 3, 4, 5, 6];  \nconsole.log(array.length); \/\/ 6  \narray.length = 3;  \nconsole.log(array.length); \/\/ 3  \nconsole.log(array); \/\/ [1,2,3]<\/code><\/pre>\n

 <\/p>\n

9. Replace the whole<\/h3>\n

The function String.replace()<\/code>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()<\/code>using the \/g<\/code>last Regex:<\/p>\n

var string = \"john john\";  \nconsole.log(string.replace(\/hn\/, \"ana\")); \/\/ \"joana john\"  \nconsole.log(string.replace(\/hn\/g, \"ana\")); \/\/ \"joana joana\"<\/code><\/pre>\n

 <\/p>\n

10. Include arrays<\/h3>\n

If you need to include two arrays, you can use the function Array.concat()<\/code>:<\/p>\n

var array1 = [1, 2, 3];  \nvar array2 = [4, 5, 6];  \nconsole.log(array1.concat(array2)); \/\/ [1,2,3,4,5,6];<\/code><\/pre>\n

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)<\/code>. Instead of creating a new array, it will enclose the second array into the first array, thereby reducing memory usage:<\/p>\n

var array1 = [1, 2, 3];  \nvar array2 = [4, 5, 6];  \nconsole.log(array1.push.apply(array1, array2)); \/\/ [1,2,3,4,5,6];<\/code><\/pre>\n

 <\/p>\n

11. Convert NodeList to array<\/h3>\n

If you run the function document.querySelectorAll(\"p\")<\/code>, it returns an array containing the DOM – NodeList object. But this object does not have the full array of functions such as: sort()<\/code>, reduce()<\/code>, map()<\/code>, filter()<\/code>. 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)<\/code><\/p>\n

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

 <\/p>\n

12. Scramble the elements in the array<\/h3>\n

To tamper with array elements without using private libraries like Lodash, just use the following trick:<\/p>\n

var list = [1, 2, 3];  \nconsole.log(list.sort(function() {  \n    return Math.random() - 0.5\n})); \/\/ [2,1,3]<\/code><\/pre>\n

 <\/p>\n

Conclude<\/h3>\n

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!<\/p>\n","protected":false},"excerpt":{"rendered":"

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:<\/p>\n","protected":false},"author":1,"featured_media":608,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[86],"tags":[87,88,89],"_links":{"self":[{"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/posts\/8562"}],"collection":[{"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/comments?post=8562"}],"version-history":[{"count":0,"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/posts\/8562\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/graphenelive.in\/wp-json\/"}],"wp:attachment":[{"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/media?parent=8562"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/categories?post=8562"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/graphenelive.in\/wp-json\/wp\/v2\/tags?post=8562"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}