Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in javascript, argument order of evaluation and delayed evaluation

Tags:

javascript

  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.

like image 369
cc young Avatar asked Jan 30 '26 05:01

cc young


2 Answers

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.

like image 173
Wayne Avatar answered Jan 31 '26 20:01

Wayne


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?


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!