Why do two identical statements return different results, only brackets, enclosing one and not the other?

Why do two identical operators return different results with just brackets wrapping one and not the other?

function foo(bar){ return !bar; }(false) ? false : true; // returns true 

 (function foo(bar){ return !bar; }(false) ? false : true); // returns false! why?! 
+4
source share
3 answers
 function foo(bar){ return !bar; } (false) ? false : true 

looks like:

 if(false){ //false } else { //true } 

your function is not called, and your condition is false , that is, it returns the second operator (which has //true ).


the second is VERY different

 (function foo(bar){ return !bar; } (false) ? false : true) 

as follows:

 function foo(bar){ return !bar; } var temp = foo(false) if(temp){ //false } else { //true } 

you technically create a function self-executing function expressions (IFFE) are invoked immediately using the false as parameter. what he returns obeys the condition. So:

  • you passed false as a parameter
  • the function returns the inverse that is true
  • the result is computed, and since return is true , it executes the first statement of your condition (which has //false )

self- executing functions immediately called function expressions (IFFEs) usually have these forms and are usually used for closing forms (which is beyond the scope of this question)

 var result = (function(innerParam){ //function body }(passedParam)); and //this form commonly seen in jQuery plugins var result = (function(innerParam){ //function body })(passedParam); 
+5
source

Try the following:

 function foo(bar) { alert('fun 1 executed'); return !bar; } (false) ? false : true; // returns true 

And this:

 (function foo(bar) { alert('fun 2 executed'); return !bar; } (false) ? false : true); 

Note that in case 1, the function is never called.

+1
source

This is not for me.

http://jsfiddle.net/JPv3j/1/

But in any case, this is a strange construct that you probably should not use, first of all, if it has the ability to be misinterpreted.

0
source

Source: https://habr.com/ru/post/1399620/


All Articles