JavaScript shorthand conditional statement (recommended) _javascript tips

Source: Internet
Author: User
Tags anonymous

Often in the code of the cattle everywhere see many shorthand conditional expression statements, read some articles about this, feel 3 ways 2 s ay iF This article (http://www.thomasfrank.se/3_ways_2_say_if.html) is not bad. In this article, the author of the traditional If...else ...,?:, &&/| | The characteristics and usefulness of three kinds of conditional expressions are summarized and summarized as follows:

1. If...else structure

Set R to 0 or 1 
var r= math.floor (2*math.random ()) 
 
//Set A, B and C to "small" if r==0 a else Set them to " Big ' 
//using three different techniques 
 
//method 1:if else 
var A; If (r==0) {a = ' small '} else {a = ' big ' }; 
 
Method 2:conditional operator 
var b = r==0? "Small": "Big"; 
 
Method 3:and/or Operators 
var c = r==0 && "Small" | | "Big"; 
 
Check the values of our variables 
alert (r+ "+a+" "+b+" "+c);

2. IF...ELSE If...else Structure

Set R to 0,1,2 or 3 
var r= math.floor (4*math.random ()) 
 
//Set A, B and C to "Nada", "small", "big" and "huge" 
   
    //depending on the value or r using three different techniques 
 
//Method 1:if.. else If ... else 
var A; 
if (r==0) {a= "Nada"} 
else if (r==1) {a= "small"} 
else if (r==2) {a= "big"} 
else {a= "huge"}; 
 
Method 2:conditional Operators 
var b = 
r==0? "Nada" 
: R==1? "Small" 
: r==2? "Big" 
: "huge"; 
 
Method 3:and/or Operators 
var c = 
r==0 && "Nada" | 
| r==1 && "small" | 
| r==2 && Amp "Big" 
| | "Huge"; 
 
Check the values of our variables 
alert (r+ "+a+" "+b+" "+c);
   

3. Executive function

Set R to 0,1,2 or 3 
var r= math.floor (4*math.random ()) 
 
//The global variable x and we four functions 
var X= ""; 
Nada=function () {x+= "nada! "}; 
Small=function () {x+= "small! "}; 
Big=function () {x+= "big! "}; 
Huge=function () {x+= "huge! "}; 
 
Call a specific function depending on the value of R 
//using three different techniques 
 
//method 1:if. Els E If ... else 
if (r==0) {nada ()} 
else if (r==1) {small ()} 
else if (r==2) {big ()} 
else {huge ()}; 
 
Method 2:conditional Operators r==0 nada (): R==1? Small (): r==2 
-Big () 
: Huge (); 
 
Method 3:and/or Operators 
r==0 && (Nada () | | true) the//nada () function does not necessarily return true, in order to ensure subsequent logic or | | Judgment is not executed, return true value, same as
| | r==1 && (small () | | true) 
| | r==2 && (BIG () | | true) 
| | huge (); 
   //Check The values of our variables 
alert (r+ "+x)";

4. Execute code

//Set R to 0,1,2 or 3 var r= math.floor (4*math.random ())//The global variable x VA 
 
R x= ""; Executing different code depending on the value of R//using three different techniques//method 1:if. else If ... else if (r==0) {x+= "nada! "} else if (r==1) {x+=" small! "} else if (r==2) {x+=" big! "} else {x+=" huge! 
 
"}; Method 2:conditional operators r==0? function () {x+= "nada! "} (): R==1? function () {x+= "small! "} (): R==2? function () {x+= "big! "} (): function () {x+=" huge! 
 
"}(); Method 3:and/or Operators R==0 && (function () {x+= "nada! "}() || true)//someone commented in the comments that anonymous functions here are not necessary, in the case of only one executable code, but if there are multiple code to be executed, the anonymous function is good | | R==1 && (function () {x+= "small! "}() || True) | | r==2 && (function () {x+= "big! "}() || True) | | function () {x+= "huge! 
 
"}(); Check the values of our variables alert (r+ "" +x); 

In this web article, the author's focus is on the brevity of the code, so in general, to achieve the same function, the author is more inclined to use?: Operators, and feel && | | The way to play a few more letters, and thus appear more cumbersome. In the case of function execution, it is more convenient to use traditional if...else. In its comments, it has been suggested that making client-side code simpler and shorter than improving some obscure operational efficiencies is also true in some ways. So from a formal selection of a more concise form of processing conditional statements, may be more important than the operational efficiency of these statements themselves, not to mention the operational efficiency will vary according to UA.

In the judgment of only two conditions, the If...else or the: are fairly straightforward, while && and | The operation of the method is slightly too complicated. But in fact, if you understand the following two basic principles, all the problems will be solved:

First, when using logic with && and logic or | | operator operations, the direction is from left to right,&& to the first value of false (or a value that can be converted to false, such as null/undefined/0/""/nan, etc.). The operation is stopped when the first value is true (or a value that can be converted to true); The value returned by the entire condition is the value of the last detected condition, not necessarily just true/false.

The second, the logic and the && operator than the logical OR operator, the former has a higher priority.

According to the first principle, r==0 and "small" are computed from left to right, and if r==0 is true, detect "small", "small" is a non-empty string, so C takes a value of "small", and if R==0 is false, the logical OR | | The second condition "big" detection, the same reason, C should take the value of "big". According to the second principle, there is no need for parentheses in the operation of the variable C in the preceding code.

Because of use?: And &&, | | Operators are useful for streamlining code in a certain program, and are important in library source code such as jquery. To sum up, these operators have two main applications, one is the assignment or return value, and the other is to execute the code (for the moment this classification).

Usage for assignment is ubiquitous in jquery or other libraries, and a classic application is the ability to implement default values for interfaces, and we can easily write code such as:

var myobj = function (options) {
  var color = Options.color | | this.defaults.defaults;
  var backgroundcolor = Options.backgroundcolor
      | | this.defaults.backgroundColor;
MyObj.prototype.defaults = {
  color: "#393939",
  backgroundcolor: "#222"
}
var myins = new MyObj ({
  Color: "#80FF80"
});
Console.log ("Color:" +myins.color+ ", BackgroundColor:" +myins.backgroundcolor);

No use?: && and | |, because they do not have the inherent code block functionality (with the {} number package), they can only execute a single line of code, such as: If...else

(xmlhttprequest.readystate==4 && xmlhttprequest.status ==200)? Alert ("success!"): Alert ("failure!");

So if you have more than one code to execute, you should use an anonymous function. Such as:

(xmlhttprequest.readystate==4 && xmlhttprequest.status ==200)? function () {alert ("success!"); var a=100; alert (a);: Alert ("failure!");

In the jquery 1.7.1 source code These two shorthand forms are too many, as line 2643 has:

Hook for boolean attributes
Boolhook = {
  get:function (elem, name) {
    //Align Boolean attributes with Cor Responding properties
    //Fall back to attributes presence where some booleans are not supported
    var attrnode,
      P Roperty = Jquery.prop (elem, name);
    return property = = = True | | 
typeof Property!== "Boolean" && (Attrnode = Elem.getattributenode (name)) && Attrnode.nodevalue!== Fals E?
      Name.tolowercase ():
      undefined
  },
  set:function () {
...
  }
}

It seems that we have to continue to study to summarize.

The above JavaScript shorthand conditional statement (recommended) is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.

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.