12 extremely useful hacks for JavaScript
In this post I will share 12 extremely useful hacks for JavaScript. These hacks reduce the code and will 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 has a valid value, to consider them as true value. For do this kind of validation, you can use the !! (Double negation operator) a simple !!variable, which will automatically convert any kind of data to boolean and this variable will return false only if it has some of these values: 0, null, "", undefined or NaN, otherwise it will return true. To understand it in practice, take a look this simple example:
In this case, if an account.cash value is greater than zero, the account.hasMoney will be true.
function Account(cash) {
this.cash = cash;
this.hasMoney = !!cash;
}
var account = new Account(100.50);
console.log(account.cash); // 100.50
console.log(account.hasMoney); // true
var emptyAccount = new Account(0);
console.log(emptyAccount.cash); //
console.log(emptyAccount.hasMoney); // false
2) Converting to number using + operator
This magic is awesome! And it’s very simple to be done, but it only works with string numbers, otherwise it will return NaN (Not a Number). Have a look on this example:
function toNumber(strNumber) {
return +strNumber;
}
console.log(toNumber("1234")); //
console.log(toNumber("ACB")); // NaN
This magic will work with Date too and, in this case, it will return the timestamp number:
console.log(+new Date()) //
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 will be verified) and a function using the&& (AND operator) between both. For example, the previous code can become smaller in one line:
conected && login();
You can do the same to 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 in old browsers you can use the || (OR operator) by including the default value as a second parameter to be used. If the first parameter returns false the second one will be used as a default value. See this example:
function User(name, age) {
this.name = name || "Oliver Queen";
this.age = age || 27;
}
var user1 = new User();
console.log(user1.name); // Oliver Queen
console.log(user1.age); //
var user2 = new User("Barry Allen", 25);
console.log(user2.name); // Barry Allen
console.log(user2.age); //
5) Caching the array.length in the loop
This tip is very simple and causes a huge impact on the performance when processing large arrays during a loop. Basically, almost everybody writes this synchronous for to iterate an array:
for(var i = 0; i < array.length; i++) {
console.log(array[i]);
}
If you work with smaller arrays – it’s fine, but if you process large arrays, this code will recalculate the size of array in every iteration of this loop and this will cause a bit of delays. To avoid it, you can cache thearray.length in 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 is very useful when you need to check if some attribute exists and it avoids running undefined functions or attributes. If you are planning to write cross-browser code, probably you will use this technique too. For example, let’s imagine that you need to write code that is compatible with the old Internet Explorer 6 and you want to use the document.querySelector(), 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 operator, see this example:
if ('querySelector' in document) {
document.querySelector("#id");
} else {
document.getElementById("id");
}
In this case, if there is no querySelector function in the document object, we can use thedocument.getElementById() as fallback.
7) Getting the last item in the array
The Array.prototype.slice(begin, end) has the power to cut arrays when you set the begin and endarguments. But if you don’t set the end argument, this function will automatically set the max value for the array. I think that few people know that this function can accept negative values, and if you set a negative number as begin argument you will get the last elements 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) 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 you want to set. For example, if you have an array with 10 elements, but you want to get only the first five elements, you can truncate the array, making it smaller by setting thearray.length = 5. See this example:
var array = [1,2,3,4,5,6];
console.log(array.length); //
array.length = 3;
console.log(array.length); //
console.log(array); // [1,2,3]
9) Replace all
The String.replace() function allows using String and Regex to replace strings, natively this function only replaces the first occurrence. But you can simulate a replaceAll() function by using the /g at the end of a Regex:
var string = "john john";
console.log(string.replace(/hn/, "ana")); // "joana john"
console.log(string.replace(/hn/g, "ana")); // "joana joana"
10) Merging arrays
If you need to merge two arrays you can use the Array.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 most suitable to merge large arrays because it will 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 will merge the second array in the first one reducing the 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) Converting NodeList to Arrays
If you run the document.querySelectorAll("p") function, it will probably return an array of DOM elements, the NodeList object. But this object doesn’t have all 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 this technique just use this function: [].slice.call(elements):
var elements = document.querySelectorAll("p"); // NodeList
var arrayElements = [].slice.call(elements); // Now the NodeList is an array
var arrayElements = Array.from(elements); // This is another way of converting NodeList to Array
12) Shuffling array’s elements
To shuffle the array’s elements without using any external library like Lodash, just run this magic trick:
var list = [1,2,3];
console.log(list.sort(function() { Math.random() - 0.5 })); // [2,1,3]
Conclusion
Now you learned some useful JS hacks which are largely used to minify JavaScript code and some of these tricks are 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 how you 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 was posted in JavaScript, Tutorials and tagged hacks, javascript by Caio Ribeiro Pereira. Bookmark the permalink.
12 extremely useful hacks for JavaScript的更多相关文章
- 12个非常有用的JavaScript技巧
在这篇文章中,我将分享12个非常有用的JavaScript技巧.这些技巧可以帮助你减少并优化代码. 1) 使用!!将变量转换成布尔类型 有时,我们需要检查一些变量是否存在,或者它是否具有有效值,从而将 ...
- 12个十分实用的JavaScript小技巧
12个非常实用的JavaScript小技巧 在这篇文章中将给大家分享12个有关于JavaScript的小技巧.这些小技巧可能在你的实际工作中或许能帮助你解决一些问题. 使用!!操作符转换布尔值 有时候 ...
- 12个非常实用的JavaScript小技巧
在这篇文章中将给大家分享12个有关于JavaScript的小技巧.这些小技巧可能在你的实际工作中或许能帮助你解决一些问题. 使用!!操作符转换布尔值 有时候我们需要对一个变量查检其是否存在或者检查值是 ...
- 12个非常有用的JavaScript小技巧
在这篇文章中将给大家分享12个有关于JavaScript的小技巧.这些小技巧可能在你的实际工作中或许能帮助你解决一些问题. 使用!!操作符转换布尔值 有时候我们需要对一个变量查检其是否存在或者检查值是 ...
- 【转】网上看到的“12个非常有用的JavaScript技巧”
1) 使用!!将变量转换成布尔类型 有时,我们需要检查一些变量是否存在,或者它是否具有有效值,从而将它们的值视为true.对于做这样的检查,你可以使用!!(双重否定运算符),它能自动将任何类型的数据转 ...
- (网页)12种不宜使用的Javascript语法(转)
转自阮一峰: 最近写的一些小东西,总是出各种各样的问题,用了angular.js反应居然比我的jQuery还慢,客户吐槽了,我又把一个小操作,改成了jQuery.浏览一下大神的的博客.转载一点东西: ...
- 12种不宜使用的javascript的语法
1. == Javascript有两组相等运算符,一组是==和!=,另一组是===和!==.前者只比较值的相等,后者除了值以外,还比较类型是否相同. 请尽量不要使用前一组,永远只使用===和!==.因 ...
- 12个非常不错的javascript类库
Javascript是一个解释性的编程语言.最初作为浏览器的一部份在浏览器中运行,可以和用户交互,并且控制浏览器,异步通讯,修改显示的document.在这篇文章中,我们收集了12款最新的Javasc ...
- 12种不宜使用的Javascript语法
Douglas Crockford列出了12种应该避免使用的Javascript语法,我觉得非常值得推广. ============================== 1. == Javascrip ...
随机推荐
- 【再话FPGA】在xilinx中PCIe IP Core使用方法
采用Xilinx Virtex-5 XC5VSX50T-FF1136 FPGA或者Xilinx Virtex-5 XC5VSX95T-FF1136的板子.采用ISE13.2环境.步骤:一.建立一个IS ...
- [na]ping提示&各系统默认的TTL值
1,Win7 ping 不存在的地址(请求超时) ip routing和no ip routing no ip routing----不查路由表 不配置网关---arp-catch中存在很多条目(相当 ...
- vue2.x 路由懒加载 优化打包体积
当打包构建应用时,Javascript 包会变得非常大,影响页面加载.如果我们能把不同路由对应的组件分割成不同的代码块,然后当路由被访问的时候才加载对应组件,这样就更加高效了. 结合 Vue 的异步组 ...
- zabbix 实现 iptables 监控
安装iptstate # yum install iptstate 配置zabbix key iptables.conf # cat /etc/zabbix/zabbix_agentd.d/iptab ...
- 使用putty部署远程J2EE环境
以前没弄过,开个帖子记录一下. 基本上要做的就是安装JDK.安装tomcat.安装sql. 1.安装JDK JDK在本机上,需要传输到远程linux服务器上.为了存放我们上传的文件.打开putty,进 ...
- socket.io笔记三之子命名空间的socket连接
当客户端发送admin命名空间下的连接,如果主连接也监听了connetion事件,主连接的connection事件会先触发执行,然后紧接着触发执行admin命名空间下的connection事件.如果客 ...
- 无法加载 DLL“ParkCOM.dll”: 找不到指定的模块。 (异常来自 HRESULT:0x8007007E) 终结者
C#调用利用C++写的dll 常遇到的情况是无法加载DLL"***.dll":找不到指定的模块(异常来自HRESULT:0x8007007E)终极解决方法如下: 1.产生原因 可能 ...
- Python2.7 fabric理论学习
在python中有一个可以实现批量管理服务器的工具:fabric,在本地和远程机器上提供了一些基本的操作,并且可以上传/下载文件.执行sudo等功能. 学习环境:ubuntu 12.10+python ...
- CSAPP 读书笔记 - 2.31练习题
根据等式(2-14) 假如w = 4 数值范围在-8 ~ 7之间 2^w = 16 x = 5, y = 4的情况下面 x + y = 9 >=2 ^(w-1) 属于第一种情况 sum = x ...
- 【Acm】八皇后问题
八皇后问题,是一个古老而著名的问题,是回溯算法的典型例题. 其解决办法和我以前发过的[算法之美—Fire Net:www.cnblogs.com/lcw/p/3159414.html]类似 题目:在8 ...