In need of a custom function to append an element to the end of an array, I encountered a requirement: if this new element shares its value with any existing elements in the array, it should not be appended. For instance, adding 2 to [1,2] should result in [1,2] only.
This is the code snippet I came up with:
function add(arr, elem) {
if (arr.indexOf(elem) != -1){
return arr;
}
else {
let newArr = arr.push(elem);
return newArr;
}
}
console.log(add([1,2],3)); // Expected output: [1,2,3], but received '3' instead
Can anyone shed light on why the 'newArr' array was not returned in the else block, and a number was returned instead?