Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.javascript > #30090

Re: Can somebody explain this code

From tony@mountifield.org (Tony Mountifield)
Newsgroups comp.lang.javascript
Subject Re: Can somebody explain this code
Date 2016-03-23 23:46 +0000
Organization Software Insight Ltd., Winchester, UK
Message-ID <ncv9sp$9b2$1@softins.softins.co.uk> (permalink)
References <ncv2un$mlp$1@dont-email.me>

Show all headers | View raw


In article <ncv2un$mlp$1@dont-email.me>,
Tony Johansson <johansson.andersson@telia.com> wrote:
> I know that functions behave much like variables such as
> var myFunc = function() { alert("This is my anonymous function");}
> 
> But in the code below when I have (a && b)(); only function b is called and
> when I have  (a || b)();  only function a is called
> 
> If a = null in this example (a || b)();   then b is called.
> 
> Can somebody explain what is happening here when I have this kind of strange 
> looking code.
> I do this just because of some testing how it works.
> 
> If both a and b is null I get error because then the expression does not 
> produce a function value which is correct.
> 
> <script type="text/javascript">
>         function a()
>         {
>             alert("function a");
>         };
> 
>         function b()
>         {
>             alert("function b");
>         };
> 
>        (a && b)(); //here only b is called

The expression (a && b) returns a if a is not truthy, but returns b if a is truthy.
In this case a and b are pointers to functions, which are always truthy. So (a && b)
has the value b, which is then called by virtue of the following ().

>         (a || b)(); // here only a is called

The expression (a || b) returns a if a is truthy, otherwise returns b. So (a || b)
always has the value a when a is a function pointer, and this gets called by the ().

>     </script>
> 
> //Tony 

Cheers
Tony (another one!)
-- 
Tony Mountifield
Work: tony@softins.co.uk - http://www.softins.co.uk
Play: tony@mountifield.org - http://tony.mountifield.org

Back to comp.lang.javascript | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Re: Can somebody explain this code tony@mountifield.org (Tony Mountifield) - 2016-03-23 23:46 +0000
  Re: Can somebody explain this code Aleksandro <aleksandro@gmx.com> - 2016-03-23 23:58 -0300
  Re: Can somebody explain this code Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-03-24 04:20 +0100
    Re: Can somebody explain this code "Evertjan." <exxjxw.hannivoort@inter.nl.net> - 2016-03-24 11:23 +0100
      Re: Can somebody explain this code Thomas 'PointedEars' Lahn <PointedEars@web.de> - 2016-03-24 20:32 +0100
    Re: Can somebody explain this code John Harris <niam@jghnorth.org.uk.invalid> - 2016-03-24 11:22 +0000

csiph-web