# JavaScript comma operator

Source: Internet
Author: User
Tags tagname

The C at the end is the lowest-priority comma operator. The comma operator is the last line of operator precedence and rarely an article records, which hides its sharpness. It may not be a strong JavaScript operator, but I like it. It's simple, elegant and you should make it your friend. So, let's get started-you need to learn more about JavaScript, the shy hero.

What does it do?

The comma operator evaluates its operand (left to right) and returns the value of the second operand. (MDC)

`var a = (7, 5); A;    // 5 var  = (Y=1, z=4); x;    // 4y;   // 1z;   // 4`

Why do you put these variables in parentheses?

Because of the precedence of the operator. A JavaScript statement can protect several different operators, and the following statement contains three operators (*,+ and,);

`return 5 * 2 + 3, 22;`

The operator precedence in one statement determines the order in which operators are executed. The complete list of operator precedence is here. The comma operator is the least-precedence operator for all operators. Let's simulate how the above example works:

`// the original return 5 * 2 + 3,  ; // Run * operator return + 3,; //Run + operator return to; //Run , operator return 22;`

Now let's use this knowledge to see what happens if we don't put these variables in parentheses: It effectively has the highest priority. Ensure that operator operators take precedence:

`// Original Statement var a = (7, 5); // Execution Group var a = 5;`

`// Original Statement var a = 7, 5; // Run = operator var a, 5;  // A is now equal to 7 // syntaxerror:missing variable name`

By putting the expression on the right side of the equal sign in parentheses, we create a group-it effectively has the highest priority. This ensures that the comma operator can be executed first:

`// Original Statement var a = (7,5); // Run Group var a = 5;`

In practice, the lowest operator precedence does make the comma operator very powerful. In fact, the comma operator says, "Go ahead and look at all the other small operators before you come to my duel."

Some statements contain multiple commas. How do they work?

The above rules still apply. Each comma operator in the statement runs from left to right in an orderly manner.

`var a = (1, 2, 3, 4); A;   // 4`

This equals:

`var a = (((1, 2), 3), 4); A;   // 4`
What about commas for text types and declarations?

These are comma delimiters instead of comma operators. The purpose of the comma delimiter is to divide the members into lists. For example:

`// set 4 elements of an array var arr = [1, 2, 3, 4]; // create an object with 2 attributes var obj = {    ,    function() {return This this. A}}// defines 3 different variables var a = 1, b = 2, c = 3; // call a function and pass 2 arguments Math.max (4, 7);`
Why use the comma operator?

Because they let you specify multiple expressions, JavaScript expects only one. Comma operators are rarely necessary, but are often useful and occasionally very elegant:

`1 varr = [], n = 0, a = 0, B = 1, Next;2 3 functionNextfibonacici () {4Next = a +b; 5return b = (a=b, next);      6 }7 8  while(N++ < 10){9 R.push (Nextfibonacici ();)Ten } One  AR//[1, 2, 3, 5, 8, , +,----]`
`functionGetrandomprime () { while (n = Math.Round (Math.random () *1000000000),!IsPrime (n)); returnN;}varIsPrime =function(n) {d=Math.ceil (MATH.SQRT (n));  while(n% (d--) &&d); return!D;}  Getrandomprime (); //298207139Getrandomprime ();//308547853`
is the comma operator just a fake semicolon?

The semicolon operator separates the statements. The comma operator separates the expressions in the statement.

Why not use logic and && operators to evaluate the order of multiple expressions?

The comma operator is an intimate cousin of logic with && and logic or operator. Three operators will return the last expression they evaluated. Their differences are also simple:

`1 //(lhe:left hand expression, RHE right hand expression)2 3LHE &&RHE41the expression on the left is always executed.52if the left is true, perform the right6 7LHE | |RHE81The left expression is always executed.92If the left side is false, perform the rightTen  One LHE, RHE A1always executes the left-hand expression -2. Always perform the right-hand expression`

When all two expressions must be executed, select the comma operator.

Good. I mentioned earlier that the comma operator lets you specify multiple expressions, and JavaScript only orders one. This may be the scope of the For loop:

For loops

This is another version of Fibonacci, and also uses the comma operator:

` for (    var i = 2, r = [0,1];    I<15;     R.push (r[i-2]+r[i-1]), i++); r;    // [0, 1, 1, 2, 3, 5, 8,, 144, 233, 377]`

Another example, a practical example, helps the clerk to select banknotes and coins for the customer. The following is a basic version. We use the comma operator to divide the second expression of a For loop. This allows us to add a currency calculator before testing the constraint expression:

`function tocurrency (total, values) {   *=;     for (       var i =0, counts = [];        = Total/values[i], total = total% values[i];       i++);    return Counts.map (Math.floor);} Tocurrency (32.47, [Max, 5, 1]);  // [6, 2, 1, 2, 0, 2]`

Now the following is the same practical example, adding a user-friendly format:

`functiontocurrency (total, values, sym)*= 100; //Do the calc     for(        varI=0, counts = []; Counts[i]=total/values[i],total=total%values[i]; i++    ); //format    varResults = Counts.map (function(s,i) {returnS>=1&&[math.floor (s), "X", (Sym | | ' \$ ') + (values[i]/100). toFixed (2)].join (");    }); returnResults.filter (Boolean). Join (', ');} Tocurrency (19.77, [500,100,25,10,5,1]);//"3 x \$5.00, 4 x \$1.00, 3 x \$0.25, 2 x \$0.01"Tocurrency (19.77, [500,100,50,20,10,5,1], ' £ ');//"3 x£5.00, 4 x£1.00, 1 x£0.50, 1 x£0.20, 1 x£0.05, 2 x£0.01"Tocurrency (19.77, [500,100,50,20,10,5,2,1], ' € ');//"3 x€5.00, 4 x€1.00, 1 x€0.50, 1 x€0.20, 1 x€0.05, 1 x€0.02"`

The following function uses the comma operator in a for loop to increase and decrease the number of two counters at the same time. The counter is used to render attractive curves on the console:

`function Rendercurve () {    for (var a=1,b=10;a*b;a++,b--)        console.log (New Array (a*b). Join (' * '));} Rendercurve ()/*************************************************************************** *************************************************************************************************************** **************************/`
While loop

You can use the comma operator to create a concise do-while loop version. The search tag matches the ancestor of the element. We use commas again to check the restriction expression:

`function firstancestor (el, tagName) {  while (el = El.parentnode, El && (el.tagname! =  Tagname.touppercase ()));   return  //element in http://ecma262-5.com/ELS5_HTML.htmvar a = \$ (' section_15.1.1.2 ' );   // <div class= "page" >`
Ternary conditions

Ternary syntax allows only one expression per three components. As a general rule, if you want to use multiple declarations, you need to consider using if else. However, it is sometimes more readable to use the comma operator in ternary expressions to compare simple expressions:

`// player loseslives? (Lives--, Go ()):(Gameover (), exit ());`
Debugging

The comma operator provides a low-key way to inject the console logs into your code without reformatting it (can you find errors that require debugging in each case?). ）。。。

`// contains a deliberate error!!!! // total output when i>n var i=10,n=0,total=0;  while (Console.log (i,n), i-->n++); {    + = i*n} /* Ten-524 */`
`// contains a deliberate error!!!! // Total is an array var arr = [n/a];  for (    var i=0, total=0;    I<arr.length;     + = arr[i++]); /* 0 3 */`

`// contains a deliberate error!!!  // array member increased by 4 and summed //(yes there is an easier way to do this)var testarray = [3, 5, 8, 4], total = 0; var plusfour = Testarray.map (function(e) {e + 4});p Lusfour.foreach (function( N) {console.log (n), IsNaN (n) | | (Total + = N)}); /* undefinedundefinedundefinedundefined */`
Iterator bindings
`var colorindex = 0,     = ["FF0000", "008000", "FF0086", "a2ff00", "0000FF", "800080"   function  selectnextcolor () {    return colors[colorindex++] | | colors[colorindex = 0, colorindex++];}`
Indirect call Eval

Eval1 are usually called in their containing context (for example, the this value in the operation code is the same as the this value of the surrounding code). This is problematic because there is no guarantee that duplicate eval calls originate from the same context.

As Kangax describes, we can call eval indirectly using the stylish comma operator which will force it to execute 2 in the global context:

` var  a = {};  // attempt eval in context of object <code>a</code>  (function   () {eval ( "This.alert (' If You Can read this I must is global! ') "  // typeerror:this.alert is not a function  // force eval in global context  (function   () {( 0,eval) ("This.alert (' If Can read this I must is global! ') "  // alerts: ' If You can read the I must be global! '  `

The discussion of the merits of ¹eval is beyond the scope of this article.

² Although the ES5 standard confirms that an indirect call to Eval should run globally, not all browsers are compatible (for example, ie<=8).

Summary

You may not use the comma operator, but you can write good JavaScript code. Does that mean I just wasted your time? I hope not. Just as a broad vocabulary makes us a better speaker and author, so extensive exposure to language features makes us a better programmer. The more technology we can dictate, the more we have the ability to write elegant, concise, readable code.

Write interesting code with the comma operator, and share your neat usage examples!

https://javascriptweblog.wordpress.com/2011/04/04/the-javascript-comma-operator/

JavaScript comma operator

Related Keywords:
Related Article

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.