Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
how to call function with sometimes less argument

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

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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);
}
about 4 years ago · Juan Pablo Isaza Report

0

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);

about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!