I don't know how to make function arguments to be optional in a certain case. The case is if I have at more than one argument and not the last one should be optional. I see the ejs templating engine solves this:
ejs.renderFile(templatesPath, options, (err, html) => {
if (err) {
console.log(err);
error = err;
} else {
res.write(html);
res.end();
}
})
So if I don't pass the options parameter, the callback function will still be recognized as a callback function and not as the options object - and the role, assigned to it, remains to be callback function and not the role of the missed parameter - as it would normally.
So how can it be solved - in JavaScript - that I still define 2-3 or more arguments (in the function definition) but if I don't pass an optional one - which is not the last - that it doesn't change the passed parameters role.
What matters is the order of the parameters. Therefore, you must repect it.
Just pass undefined
, null
or an empty object {}
if the function does not support no value.
Below, options
is declared but not valued (undefined
). The order is respected, it will work.
You can keep this way: always declare variable to pass them to the function, and assign value to them only when you have it.
var options;
ejs.renderFile(templatesPath, options, (err, html) => {
if (err) {
console.log(err);
error = err;
} else {
res.write(html);
res.end();
}
});