There is no "better" without criteria, although we can probably infer some criteria here. :-)
Using push
without making a copy (your "NOT" option) mutates the original array passed to your function (the global one), which is usually not done in functional programming. FP tends to embrace using immutable data structures and pure functions (loosely: functions without side effects).
If you don't want to mutate the global array, use spread or concat
or similar. For instance, with spread syntax (no need for push
after, we can include value
in the array literal):
let newArray = [...arr, value];
let globalArray = [1, 2, 4];
function add (arr, value) {
const newArray = [...arr, value];
return newArray;
}
const updated = add(globalArray, "red");
console.log(updated);
console.log(updated === globalArray); // false
console.log(globalArray); // unchanged
.as-console-wrapper {
max-height: 100% !important;
}
If you want to mutate the global array, use push
on the array passed in:
let globalArray = [1, 2, 4];
function add (arr, value) {
let newArray = arr;
newArray.push(value);
return newArray;
}
const updated = add(globalArray, "red");
console.log(updated);
console.log(updated === globalArray); // true!
console.log(globalArray); // changed!
.as-console-wrapper {
max-height: 100% !important;
}
...but again, that's not typically done in FP. As I understand it (I'm not deep into FP), even if you wanted to update globalArray
, you'd usually do it by reassigning it: globalArray = add(globalArray, "red")
.