Simplifying a section of JavaScript code

Source: Internet
Author: User

In the actual project, we often have the following requirements:
Get the value of a key from a map, if you find that the value of the corresponding key is NULL, create a value for the key (typically the initial value), and then save the value back to the map with the following code:

var value = map[key];if(value == null){        value = "";        map[key] = value;}

But I always feel this code is disgusting, why, too verbose, too long. In real-world projects, this is a lot of skill, and if it's everywhere, it's going to crash. The villain must die.
# #赋值操作合并
First of all, value = "" and Map[key] = value These two lines do not need to be written in two lines, are assigned, should be this can be optimized:

var value = map[key];if(value == null){        value = map[key]  = "";}
Remove if judgment

If you change the if judgment to a ternary operator, you can reduce the code as follows:

var value = map[key]; value   = (value == null) ?( map[key]  = "") : value;

If you use | | Symbols that look more convenient:

var value = map[key]; value   = value || (map[key] = "");

Of course, these two lines of code can eventually be combined into the following code:

  var value = map[key]  || (map[key] = "");

At this point, the final 5 lines of code are simplified into one line of code.
# #另外一个答案
Take this question to the company's small partner, here is another answer:

var value = map[key] = map[key]  ||  ""

# #总结
This question is not difficult, ask the small partner, some people can also give the correct answer. But usually no one to take the initiative to think.

Welcome attention to the public number:

Simplifying a section of JavaScript code

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.