cc young
cc young

Reputation: 20213

in javascript, argument order of evaluation and delayed evaluation

  1. if function( arg1, arg2 ), am I correct in believing arg1 is guaranteed to evaluated before arg2 (unlike classic C for example)?

  2. is there any way to have a function where the arguments are not evaluated, but rather evaluated on demand? for example, if( cond1 || cond2 ) evaluates cond2 if and only if cond1 is false. is it possible to write our own if-like function?

for example, could I write a function like oracle's nvl( arg1, arg2, ... ), which returns the first non-null argument, evaluating them lazily. in a regular function call, all arguments are evaluated before the function body is executed.

Upvotes: 3

Views: 518

Answers (3)

Wayne
Wayne

Reputation: 60414

Function arguments are evaluated before they're passed to the function, so what you're asking for isn't technically possible. However, you could do this:

function nvl() {
    for (var i = 0; i < arguments.length; i++) {
        var res = arguments[i]();
        if (res)
            return res;
    }
}

nvl(function() { return false; }, 
    function() { return 7; }, 
    function() { return true; });

The call to nvl returns 7.

All of the function wrappers are created, but only the bodies of the first two are evaluated inside nvl.

This isn't exactly pretty, but it would allow you to prevent an expensive operation in the body of any of the functions after the first one returning a truthy value.

Upvotes: 3

Peter Olson
Peter Olson

Reputation: 142939

  1. Yes
  2. Yes, with if(cond1 || cond2), cond2 will be evaluated iff cond1 is false.

Here is a function that return the first truthy argument:

function firstDefinedArgument(){
    for(var i in arguments){
        if(arguments[i]){
           return arguments[i];
        }
     }
 }

So, for example, firstDefinedArgument(0, null, undefined, "", "hello", "goodbye") would return "hello".

If you wanted to return the first non-null argument instead of the first truthy one, you would replace if(arguments[i]) with if(arguments[i] !== null). This function would return 0 in the above example.

Upvotes: 0

user578895
user578895

Reputation:

in your first example, yes, if you're calling a function they will be evaluated in order.

In the 2nd example, JS does not evaluate every param (just like C), e.g.:

if(true || x++){

x++ will never run.

What exactly are you trying to do?

Upvotes: 1

Related Questions