The double negation !! in Javascript

栏目: IT技术 · 发布时间: 6年前

内容简介:While working on a bug I have stumbled upon the following piece of code.I was super sure it is a mistake, and that was the root of the bug. It did not make any sense to negate a negation. You will just get the same value back.But after a bit of google-ing

While working on a bug I have stumbled upon the following piece of code.

return !!(this.isFirstOverall() || this.get('videoId'));

I was super sure it is a mistake, and that was the root of the bug. It did not make any sense to negate a negation. You will just get the same value back.

But after a bit of google-ing I have found that there is such a thing as dobule negation in Javascript .

Long story short, its purpose is to convert any expression to an actual true/false boolean value.

Take for example the follwoing expression:

const isIE8 = navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8);

This will log either an Array or null. And yes, we can evaluate null as being false. Actually, null is a falsely value to be more precise.

But, if we double negate this:

const isIE8 = !!navigator.userAgent.match(/MSIE 8.0/);  
console.log(isIE8);

An actual true/false boolean value will be outputed.

The double negation !! is not an actual operator, like && or || . It is just a sequence of two negation ! signs.

The first negation converts the data (whatever it data type it may be) to a boolean, but with the opposite value. The second negation changes the boolean again to give the actual result.

Advantages and disadvantages of using the !! double negation in Javascript

Well, it depends on what do you want to make more clear. For sure the actual code will look strange to someone (like me :sweat_smile:) who does not know about this double negation trick.

On the other side, it will provide more clear value for the actual evaluation. The result will be just true or false. For example, you will not have to wonder anymore if an empty object is considered true or false.

const result = {};
if(result) {
    // make something
}

I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

精通Nginx

精通Nginx

[瑞士]艾维利 / 陶利军 / 人民邮电出版社 / 2015-2 / 49.00元

Nginx是一个高性能的轻量级Web服务器,本书从配置文件的角度出发,介绍了多种关于 Nginx配置文件的技巧。 本书以模块化风格写成,几乎每一章都是一个独立的模块,读者将能够自由地在各个模块间切换阅读。全书分两部分,第一部分用8章内容介绍了安装Nginx及第三方模块、配置指南、使用mail模块、Nginx作为反向代理、反向代理高级话题、Nginx Http服务器、Nginx的开发以及故障排......一起来看看 《精通Nginx》 这本书的介绍吧!

HTML 压缩/解压工具
HTML 压缩/解压工具

在线压缩/解压 HTML 代码

html转js在线工具
html转js在线工具

html转js在线工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试