In JavaScript, how can I create a function with an optional parameter?

There is no syntax in Javascript that specifies that a parameter is optional (or required). All parameters are optional. If they aren’t specified they’re undefined so you need to check for that. For example, this function will in effect create a default value of 10 for the parameter:

function myfunc(someParam) {
  if (someParam === undefined) {
    someParam = 10;
  }
  ...
}

Also you can access the parameters programmatically using the arguments property.

Lastly, if you have more than about 3-4 parameters it’s generally advisable to use an anonymous object instead.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)