Recently, I received a question on some JavaScript stuff:
im not sure how it helps passing an object instead of a list of variables…
Code with a more precise explanation
Before:
function createMessageWithListOfVars(firstName, lastName, age) {
return `${firstName} ${lastName} is ${age} years old.`
}
console.log(createMessageWithListOfVars("Andreas", "Max", 30));
After:
function createMessageWithObjectDestruct({ firstName, lastName, age }) {
return `${firstName} ${lastName} is ${age} years old.`
}
console.log(createMessageWithObjectDestruct({
firstName: "Andreas",
age: 30,
lastName: "Max"
}));
Top comments (12)
Recently seen this tweet from Samantha Ming.
I think this might be the reason..
twitter.com/samantha_ming/status/1...
While this is great for functional composition and keeping code clean, I think it should be used with caution. One of the reasons as to why having too many parameters in a method is bad is that the method might be doing too much work, just because we reduce to total parameter count doesn't mean we will fix the underlying issue. Instead, rewrite/split the method into several methods that take fewer arguments.
Hey Shayne,
I absolutely agree with you.
Methods should do one thing and too much parameters are a good hint that a method perhaps could be broken up into smaller methods.
In my experience using object notation makes it easier to make changes later, and with typescript updating an object interface helps catch any errors when making that change.
Also, if you're into functional composition then having one parameter is ideal.
yesterday, I was thinking about this style of code and I found it's a good approach in functions with a lot of params.
but you shouldn't use a lot of this to keep your code clean.
Hey Mahmoud,
thanks for your comment.
What is your understanding of
keep your code clean
in this case?I mean if you used an object with properties instead of multiple params in this case you can send extra properties without keep tracking of it.
I don't know if this a big deal or not but I think it's not good to use this approach in all your app
Okay, and what's the conclusion? Which notation is better in your opinion? :)
I use object as a parameter when the number of variables is greater than two.
Tomek, great question.
I use object as a parameter when the number of variables is greater than one. Especially for using async stuff I don't want to care about the correct order.
Most of the time I also add some default parameters into the function declaration.
As you mention in your explanation, clarity and no-mistake are the most important reasons.
This is what we get for not having named params.
How would you make parameters optional?