Saturday, 27 January 2018

Javascript : optional parameters in function




Let's say I have this :




function concatenate(a, b, c) {
// Concatenate a, b, and c
}




How do I handle those calls ?



x = concatenate(a)


x = concatenate(a, b)

x = concatenate(a, c)




How can I make my function aware of the parameter I gave to it ?


Answer




Any unfilled argument will be undefined.



concatenate(a, c) is equivalent to concatenate(a, b). You cannot pass the third parameter without passing the second; but you can pass undefined (or null, I suppose) explicitly: concatenate(a, undefined, c).



In the function, you can check for undefined and replace with a default value.



Alternately, you can use an object argument to imitate keyword arguments: concatenate({a: a, c: c}).


No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...