Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are arrays as default arguments safe in Javascript?

I'm coming to Javascript from Python. In Python if you use a list or dictionary as a default argument for a function, every call sees the same object. So if you have a function like:

def append_to_list(lst=[]):
  lst.append(1)
  return lst

and then call it like:

lst1 = append_to_list()
lst2 = append_to_list()

lst2 will have value [1, 1] instead of just [1]

Does Javascript have the same issue with default arguments?

like image 244
hamdog Avatar asked Jul 02 '26 18:07

hamdog


1 Answers

It does not seem to have the same issue. Testing with function:

function append_to_list(lst=[]) {
  lst.push(1)
  return lst
}

And calling the same way returns [1] both times.

like image 81
hamdog Avatar answered Jul 04 '26 08:07

hamdog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!