In JavaScript, num = num | | 1 What are the pros and cons of this notation?

Source: Internet
Author: User

Syntax sugar, equivalent to if (!! num = = false) Num=1; Java-like num=null? 1:num

The following is an answer from a friend who knows:

It's just a shorthand method. The advantage is shorter, but in fact the disadvantage is even greater.

Do you know exactly when it will become 1?

-When NUM has a value of 0 o'clock, it will become 1!
--When NUM has a value of Nan (which most likely means an error in the previous calculation), it becomes 1!
--In addition, when the incoming value type is wrong, your program may have an error, but after this statement, you may not get an error.

These are probably not the results you want, especially because many functions may add to the handling of the special value of 0 , which often leads to errors. Even if it happens to be the result you want, the next maintainer (including yourself after 1 months) may not be able to see it!

So personal advice in a certain size of the team or project, do not use | | Short-circuit, or honestly write:

if (num = = null) num = 1

The only exception is if you know exactly which is an object and cannot be a primitive value, it can be used.
option = Option | | Defaultoption

He Shijun
Source: https://www.zhihu.com/question/20377595/answer/14948746

In JavaScript, num = num | | 1 What are the pros and cons of this notation?

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.