Is there anything I should be worried about if I write code like below. I was always told that reassigning function params was a big no-no in Javascript.
function getAddress(address, lowerCase) {
address = { ...address }
if (lowerCase) {
address.line1 = address.line1.toLowerCase();
address.city = address.city.toLowerCase();
}
return address;
}
Examples of advice:
As I understand it, the reason why some places recommend not reassigning function parameters is that doing so will also change the arguments object, which is not necessarily expected behaviour. For functions that don't use arguments, however, this should not be an issue.
For example, consider the following:
function getAddress(address, lowerCase) {
address = { ...address };
var originalAddress = arguments[0];
// Do stuff with address
}
For someone not familiar with how JavaScript works in this respect, it might be reasonable to assume that setting originalAddress like this would record the original first argument that was passed to the function. But actually, when address is reassigned, this also mutates the relevant record in arguments.
Even when you're not using the arguments object, it can be a useful practice to consider all arguments to a function to be constant and immutable, to avoid potentially introducing bugs such as through modifying an object that is passed to a function. In your example, this could be achieved like this:
function getAddress(addressArg, lowerCase) {
const address = { ...addressArg }
if (lowerCase) {
address.line1 = address.line1.toLowerCase();
address.city = address.city.toLowerCase();
}
return address;
}
In your implementation, so long as address only contains primitive properties (as opposed to properties that point to a reference value such as an object or an array) then your copying it through { ...address } should create a completely separate copy. However, this method only creates a shallow copy.
If address does contain object or array properties, but no properties that are classes or functions, then you could create a deep copy through JSON.parse(JSON.stringify(address)) instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With