4

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?

hamdog
  • 991
  • 2
  • 10
  • 24
  • 4
    you're creating a new array each time the function is called. lst2 and lst1 will be 2 identical but distinct copies of an array. in other words, no. – I wrestled a bear once. Sep 09 '19 at 19:35
  • Thanks for confirming. Just tested myself. Was surprised I couldn't find a question like this on SO already so wanted to post it as a quick reference. – hamdog Sep 09 '19 at 19:39
  • 1
    why downvoting this? – messerbill Sep 09 '19 at 19:41
  • Possible duplicate of [Are javascript arguments lazily evaluated?](https://stackoverflow.com/questions/37888881/are-javascript-arguments-lazily-evaluated) – Josh Lee Sep 10 '19 at 11:47
  • I don't think I'd be able to guess the behavior in this case based off that question. Also that says JS eagerly evaluates its arguments. Python evaluates its default args at time of function definition which would also be classified as eager. – hamdog Sep 10 '19 at 16:48

2 Answers2

2

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.

hamdog
  • 991
  • 2
  • 10
  • 24
1

In JS, you don't have that functionality as in Python.

Assuming you are using ES6:

let appendToList = (a, b=[]) => {
  b.push(1);
  return b;
}

console.log(appendToList(1));
console.log(appendToList(2));

Output:

> Array [1]
> Array [1]
lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228