I want to create a function such as:
var func = function(arg1, arg2) {
callAnotherFunc(arg1, arg2);
}
as you can see, when someone needs to call func, it needs to pass 2 args. sometimes, arg2 can be null.
Sometimes, arg2 will be null. Is there some shortcut which allows me to do this ?
var func = function(arg1, arg2) {
callAnotherFunc(arg1, arg2 || nothing);
}
So if arg2 is null, it shouldn't pass another argument to callAnotherFunc at all. I am looking for some shortcut and not if/else
I don't understand why you would want to this, maybe your intentions are beyond my understanding. You can just use default parameters
var func = function(arg1, arg2 = null) {
callAnotherFunc(arg1, arg2);
}
var callAnotherFunc = function(arg1, arg2 = null){
// console.log(arg1);
// console.log(arg2);
}
You can try something like this
How To Use ES6 Arguments And Parameters
var func = (...args) => {
callAnotherFunc(...args);
}
var callAnotherFunc = (...args) =>{
console.log(...args)
}
func(1);
func(1,2);
func(1,2,3);
You could forward all arguments which are not null by using call.
var callAnotherFunc = function(){
console.log(arguments)
};
var func = function(arg1, arg2){
//So if arg2 is null, it shouldn't pass another argument to callAnotherFunc at all.
callAnotherFunc.call(
null,
Array.from(arguments).filter(function(item, index){
return index == 0 || item !== null
})
)
};
func(1, 2);
func(1, null); //REM: Does not pass second argument
func(null, null); //REM: Does not pass second argument