Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What a strange syntax?

Tags:

javascript

I've found unknown for me code construction on JQuery site. After some formatting it looks like:

function (a,c) {
    c==null && (c=a,a=null);
    return arguments.length>0
        ? this.bind(b,a,c) 
        : this.trigger(b)
}

What does the first line of the function mean? Is it any trick or standard JS code construction?

like image 629
Sergey Metlov Avatar asked Jul 26 '11 12:07

Sergey Metlov


3 Answers

It's a trick that uses boolean short-circuit evaluation to only do the second half if the first evaluates to true. Perl has this commonly:

<something> or die

where if the first statement failed, the program ends.

Read it as

if (c == null) { c = a; a = null; }
like image 134
dascandy Avatar answered Nov 17 '22 02:11

dascandy


That's an ugly way to write

if(c==null) {
  c = a;
  a = null;
}

This utilizes the fact, that the second part of boolean && will be executed if, and only if the first part evaluates to true.

like image 41
Mchl Avatar answered Nov 17 '22 02:11

Mchl


The expression uses two JavaScript features :

  • short circuit evaluation of boolean operators: in statement context, a && (b); is equivalent to if (a) (b);
  • the comma operator to group assignment expressions: in statement context, a=b,b=c; is equivalent to { a=b; b=c }

As a result the expression is equivalent to:

if (c == null) {
    c = a
    a = null
}
like image 2
dolmen Avatar answered Nov 17 '22 04:11

dolmen