Saturday, January 27, 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

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...