Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to override default parameter in JavaScript

Tags:

javascript

I've found lots of creative ways to set default parameters in ES5 & ES6 but I have yet to see a simple example of how to override default parameters in JavaScript. Take this example:

new Connection(host, port = 25575, password, timeout = 5000)

The default timeout is fine but the port number is not. When calling this function, JavaScript always treats the second parameter as the password parameter:

myConnection = connFactory.getConnection(process.env.IP,
                                         process.env.PORT,
                                         process.env.PASSWORD)

This code results in an authentication error because the second parameter is assumed to be password. How can I override the default parameter for port without modifying the original function definition?

like image 592
Egee Avatar asked Jun 27 '26 02:06

Egee


1 Answers

You may use a config object as a parameter for your function. For example:

function foo({a='SO', b}) {
  console.log(a, b)
}

foo({b: 'Yeap', a: 'baz'}) // baz Yeap
foo({b: 'foo'}) // SO foo

It will guarantee your ordering.

like image 83
The Reason Avatar answered Jun 28 '26 14:06

The Reason