Chapter 3
Working with Function Arguments

Calling functions is arguably one of the most frequent tasks you’ll do when programming. As an author of a function, you have to decide on the parameters to receive. As a caller of a function, you have to pass the right arguments. And, from the extensibility and flexibility point of view, you may want functions to receive variable numbers of arguments. From the beginning, JavaScript is one of those few languages that has supported a variable number of arguments. But that support was very spotty—the syntax was unclear and inconsistent.

Modern JavaScript brings a breath of fresh air both for defining functions and for calling functions.

Now, when defining functions you can clearly and unambiguously convey if you intend to receive a few discrete parameters, or receive a variable number of parameters, or a mixture of both. Unlike the old arguments, the new rest parameter is a full-fledged Array object, and you can process the parameters received with greater ease; you can even use functional style code for that. And, if you choose to extend your function by adding new parameters, the default parameters makes that transition much smoother than in the past.

When calling a function, the spread operator removes the need to manually break down the values in an array into discrete parameters. That leads to less code, less noise, and more fluency. In combination with Array, you may also use the spread operator to combine values in arrays and discrete variables to pass arguments to functions that receive rest parameters.

In this chapter we’ll quickly review the old arguments and how such a powerful feature is mired with issues. Then we’ll see how the rest parameter replaces arguments, bringing all the power forward minus the perils. We’ll then switch to the function calling side and take a look at the benefits of the spread operator. Finally we’ll examine default parameters and how they interplay with rest parameters.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.237.58