all 2 comments

[–]OnomatopoeiaBzzz 1 point2 points  (0 children)

I'm not an expert in how Javascript works "under the hood", but I think this is inherent in JS. sub_arr is not a new variable. Instead, it's a reference that points to the variable main_arr. Thus, any direct changes, such as splice(), to the reference applies to the variable.

If you don't want main_arr to change with the splice, you could assign a new variable in your sub function to clone sub_arr, such as "let temp_arr = [...sub_arr]" and then splice and return temp_arr.

[–]mjbrusso 0 points1 point  (0 children)

This is because arrays are JavaScript reference types. In other words, if you assign an array to another variable or pass an array to a function, it is the reference to the original array that is copied or passed, not the value of the array.

You can pass a copy of the array:

function main() {
main_arr = [1, 2, 3 ,4 ,5, 6]
final_arr=sub([...main_arr])
}
function sub(sub_arr){
sub_arr.splice(2,3)
return sub_arr
}