Home Java 5 popular JavaScript hacks

5 popular JavaScript hacks

by admin

There are several JavaScript hacks that experienced programmers use all the time.They are not entirely obvious, especially to newcomers.These hacks take advantage of language features that have some side effects.In this article I will explain how 5 of these common hacks work.

Operator usage !! to convert to a logical value

Everything in JavaScript can be interpreted as true or false This means that ifyou put an object in the conditional operator if , it will execute either true -branch of code (when the object has the value of true ), or will execute false -branch (respectively, when the object has the value false ).
0, false, "", null, undefined, NaN – are false values. All other values return true Sometimes you may need to convert a variable to a logical value. This can be done with the !! :

var something = 'variable';!!something // returns true

On the other hand, instead of if (x== "test") you can simply write if (x) If on the other hand x will be an empty variable, it will simply execute the code from the block else

Convert string to number using the +operator

In JavaScript + – is a unary operator that returns the numeric representation of the operand or NaN if the operand does not have one. For example, with this operator you can check whether a variable x is a number (you can see this code in the library underscore ): x === +x
This method is not obvious. Most likely, you would apply the methods of parseFloat and parseInt

Defining a default value with the ||operator

In JavaScript || is an example of the execution of short circuit. This operator first analyzes the expression to its left and, if it is false, analyzes the expression to its right. In either case, it returns the first true expression. Consider the following example :

function setAge(age) {this.age = age || 10}setAge();

In this example we call the function setAge() without arguments, so that age || 10 will return 10 ( !!age == false ). This way is quite good for setting the default values of variables. In fact, this approach is equivalent to the following example :

var x;if (age) {this.age = age;} else {this.age = 10;}

First example with operator || is more succinct, so this is the way it is used all over the world.
Personally, I use this method a lot. I like its brevity and simplicity. However, it’s worth noting that with this method, you can’t set a variable to 0, because 0 is a false expression. That’s why I suggest to use this way if necessary:

this.age = (typeof age !== "undefined") ? age : 10;

Using void0 instead of undefined

Keyword void takes one argument and always returns undefined Why not just use undefined ? Because in some browsers undefined – is just a variable that can be overridden. Therefore, void 0 gives us more confidence that nothing will be accidentally broken. Although you can find this hack in the source code of many libraries, I wouldn’t recommend using it regularly since all ES5-compatible browsers do not allow to overwrite the value of undefined

Encapsulation with pattern (function() {…})()

There are only 2 types of scope in ES5 : global scope and function scope. Everything you write belongs to the global scope, which is accessible from anywhere in the code. This includes the declaration of variables and functions. But what if you want to encapsulate most of the code and leave only the interface in the global scope? Then you should use an anonymous function. Consider the following example :

(function() {function div(a, b) {return a / b;}function divBy5(x) {return div(x, 5);}window.divBy5 = divBy5;})()div // => undefineddivBy5(10); // => 2

Of all the hacks listed in this article, this one is the most harmless; you can and should use it in your projects to prevent internal logic from interacting with the global scope.
In conclusion, I would like to remind you that any code you write should be simple and understandable to other programmers. And any standard constructs provided by the language should be used first.
Some of the hacks discussed in this article can be solved more elegantly with ES6 (the next version of JavaScript). For example, in ES6, instead of age = age || 10 you can write the following :

function(age = 10) {// ...}

Another example is the pattern (function() {...})() which you probably won’t use anymore after ES6 modules will be supported by modern browsers.

Additional materials

If you want to immerse yourself in the topic JS hacks even deeper, you may find the following resources helpful :

Original article : JavaScript hacks explained
Author of the article : Yanis T

You may also like