Recently, my coding style came under scrutiny for the following snippet:
export const myFunction = (myArgument: TypeOfObject[]) => {
if (!myArgument) {
myArgument = [];
}
// do something with myArgument
}
In TypeScript, it seems that myFunction
receives a pointer called myArgument
by value. If this pointer is pointing to undefined
, I simply reassign it to an empty array. Otherwise, it remains unchanged. Therefore, neither the object pointed to nor the pointer itself are being altered within the caller's context.
This approach has been criticized as poor form, with the suggestion of an alternative method:
export const myFunction = (myArgument: TypeOfObject[]) => {
let myArgumentSecond: TypeOfObject[];
if (!myArgument) {
myArgumentSecond = [];
} else {
myArgumentSecond = [...myArgument];
}
// do something with myArgumentSecond (instead of with myArgument)
}
What are your thoughts on this? Do you believe the second version is truly superior?
Despite being in TypeScript, I consider this a broader programming question and fail to grasp the issue with the initial implementation.