Javascript Spread in function calls | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Javascript Spread in function calls

Could someone explain why do we need "null" in this case? And how to use apply for a function? Thank you. function myFunction(w,x,y,z) { console.log(w+x+y+z); } var args = [1,2,3]; myFunction.apply(null, args.concat(4));

25th May 2021, 4:00 AM
V N
V N - avatar
2 Answers
+ 2
apply() method takes two arguments. First an object, in this case myFunction will be called as that objects method, and second argument is an array. Here you just want to call a function independently using apply. So you have to specify null, so that it does not throw an error. Since you don't have a this keyword in myFunction you can use any object instead of null as a first argument
25th May 2021, 4:12 AM
Aravind Shetty
Aravind Shetty - avatar
0
in es6 we can rather use the spread operator to apply an array as arguments of a function: myFunction(...args.concat(4)); or even: myFunction(...args,4); .apply() method should be reserved for very specific cases...
25th May 2021, 9:25 AM
visph
visph - avatar