4 ms·
But passing the full object is so easy... and works so well most of the time. And with Typescript we know what is there... in theory.
by swah 4y ago
But passing the full object is so easy... and works so well most of the time. And with Typescript we know what is there... in theory.
- capableweb 4y agoBut it doesn't signal the original intent and is also reusable in less contexts... Imagine we have the two following objects: const person = {name: "John"} const book = {title: "Bible"} Only one of the following functions tell the user (developer who uses the function) A) what is actually needed for the function to work by just looking at the function signature and B) works for both objects, regardless of where `name` comes from. function sayHello(person) { console.log(`Hello ${person.name}`) } function sayHello(name) { console.log(`Hello ${name}`) } Not to mention, passing smaller things leads to less memory usage, which is generally also a good idea.
- ziml77 4y ago> Not to mention, passing smaller things leads to less memory usage, which is generally also a good idea. It's not using any more memory. Whether you pass in the person object or the string, you're putting a reference on the stack. There will be a slight speedup with the more generic one if you are accessing the name more than once in the function, but you can avoid that by storing the name in a local variable. And picking between the two isn't as straightforward as you make it out. Sure, you make it so any string can go into sayHello, but now you've introduced repetition at the call sites as they each have to pick the correct property to pass in. Also it means you can't easily change the sayHello function to do something like meeting a new requirement that it needs to greet the user more formally. If I take the whole person object, the change can be made in a single spot instead of having to modify the callers: function sayHello(person) { console.log(`Hello ${person.title} ${person.lastName}`); }