DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Discussion on: Daily JavaScript Tips #1

 
rakesh_patel profile image
Rakesh Patel

My requirement is, I don't want to remember the sequence of arguments while passing parameter to function.

function Func (fName, mName, lName) {
console.log(
full name : ${fName} ${mName} ${lName});
}

while calling above function, I must have to pass parameter's in correct order,
Func( "Elon", "Reeve", "Musk" ); //will log correct full name

What if I call function like,

Func( "Elon", "Musk", "Reeve" ); //it will log wrong full name

with Object we can avoid parameter sequence,

function Func ({fName, mName, lName}) {
console.log(
full name : ${fName} ${mName} ${lName});
}

Func({ lName : "Musk", fName : "Elon", mName : "Reeve"}); // now we can pass parameter in any order

and if you don't want to pass any parameter, then just pass default value,

function Func ({fName = "", mName = "", lName = ""}) {
console.log(
full name : ${fName} ${mName} ${lName});
}

Func({fName : "Elon"});

Now coming to your solution : OPTIONAL PARAMETER / REST OPERATOR

function Func (fName, ...args) {
console.log(
full name : ${fName} ${args[0]} ${args[1]});
}

Func( "Elon", "Musk", "Reeve" );

but even with optional parameter, I need to remember correct index no of parameter
( Respective to above function, mName only accessible by args[0])

(It will be great if you explain how OPTIONAL PARAMETER will fulfill my requirement. I will also learn something new)

Post Author have written simple JS development tips, and I don't think Typescript will resolve that issue

Thread Thread
 
dhairyashah profile image
Dhairya Shah Author

That was great explanation. Good