Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript functions with optional first parameter, but passed second parameter [duplicate]

Let's say I have a function myfunc that can take up to two parameters: arg1 and arg2:

var myfunc = function (arg1,arg2) {
  console.log(arg1,arg2);
};

I want to call the function using only arg2. However, when I run this, the input is passed to the first argument, and myfunc will log "input" undefined rather than undefined "input" as expected.

myfunc(arg2 = 'input')
> "input" undefined

Does Javascript support this type of input?

like image 301
jane Avatar asked Mar 04 '23 08:03

jane


1 Answers

Javascript doesnot support the parameters with name. But you can achieve same thing using Unpacking fields from objects passed as function parameter and passing object to function

var myfunc = function ({arg1,arg2}) {
  console.log(arg1,arg2);
};

myfunc({arg2:"input"})
like image 139
Maheer Ali Avatar answered Apr 14 '23 03:04

Maheer Ali