Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are javascript arguments lazily evaluated?

I have made a dependency injection module. It uses a hack I discovered with default parameters. function (x = SomeDependency) {}. SomeDependency is not defined, but I can parse its toString (same for class constructors, arrow functions and terse object methods). It's not meant to be supported in the browser, only in Node.

My question: I could not find any documentation on whether arguments are lazily evaluated, does any specification/documentation on this exist? Or is this simply undefined behaviour?

Update:

What I am doing is using undefined default parameters (as in the example above), and parsing the toString of the function/class to find out what they are, then calling the function or newing up the class with injected arguments.

like image 755
user3654410 Avatar asked Jan 05 '23 21:01

user3654410


2 Answers

Are javascript arguments lazily evaluated?

No. JavaScript uses applicative order evaluation

This is very easy to test too

var foo = ()=> (console.log('foo'), 'foo');
var bar = ()=> (console.log('bar'), 'bar');
var bof = (a,b)=> console.log('bof',a,b);

bof(foo(), bar());

Notice you will see "foo" and "bar" appear in the log before bof is evaluated.

This is because foo and bar are evaluated first before the arguments are passed to bof

like image 80
Mulan Avatar answered Jan 13 '23 20:01

Mulan


Are arguments lazily evaluated?

No, everything in JavaScript is eagerly evaluated (if you excuse short-circuit evaluation of logical operands).

Specifically, the default initialisers of parameters are not evaluated when the parameter is used, they are eagerly evaluated when the function is called. They are however evaluated conditionally - whenever the argument is undefined, pretty much like the statement in a if clause would be.

Does any specification/documentation on this exist?

Yes, JavaScript evaluation order is specified in the ECMAScript standard (current revision: http://www.ecma-international.org/ecma-262/7.0/). There is hardly any undefined behaviour.

like image 32
Bergi Avatar answered Jan 13 '23 20:01

Bergi