Reputation: 67
I have written a javascript project which makes extensive use of default parameters, for example:
function hello(x = true){
...
}
Now I want to call my code from the command line. I have tried using Rhino, Nashorn and Node but they all throw errors when encountering default parameters. In Rhino the error is:
js: "resource.js", line 6: missing ) after formal parameters
js: function hello(x = true){
js: ..................^
js: "resource.js", line 1: Compilation produced 1 syntax errors.
Is there some way I can call my project from the command line without having to rewrite all my code to get rid of default arguments?
Thanks
EDIT: after updating node.js to version 8 from version 4, this works. I will use node.js but I still don't know if this is possible on rhino.
Upvotes: 2
Views: 3396
Reputation: 1551
You always have a way to copy the behavior of default arguments but it won't as readable as with a newer version of javascript.
The straightforward way of doing it if you only have one argument would be an undefined
check inside your function, i.e.:
js> function hello(x){
> if (x === undefined) x = 5;
> return x;
> }
js> hello()
5
js> hello(42)
42
On the other hand, if your function contains more arguments I would recommend you to use an object as input and then check for an undefined
value, as above:
js> function hello(args){
> if (args.x === undefined) args.x = 5;
> return args.x + "-" + args.y;
> }
js> hello({y: 12})
5-12
js> hello({x: 1, y: 42})
1-42
Upvotes: 1