Search code examples
javascriptfunctionattributesfunction-calls

Javascript function call to have optional attributes


Can a function be defined in javascript in a way that attributes are optional in a function call?

for example, I have the below function defined:

function abc(x1,y1,x2,y2){
//execution
}

What I am willing to do is something like this:

function abc(x1,y1,x2,y2,id){
if(id!=''){
//do something
}else{
// do something else
}
}

function call: abc(1,2,3,4);

Will the above function still work or give an error?


Solution

  • Test it as typeof id !== 'undefined'

    function abc(x1, y1, x2, y2, id) {
      if (typeof id !== 'undefined') {
        console.log(id);
      } else {
        console.log(arguments);
      }
    }
    
    abc(1, 2, 3, 4);
    console.log('-------------------');
    abc(1, 2, 3, 4, 'YOUR_ID');