Mastering ES6 Parameter Handling: Rest, Spread, Defaults, and Destructuring
This article explains how ES6 improves JavaScript function parameters with rest parameters, spread syntax, default values, and destructuring, showing practical code examples, usage tips, and browser support details for both desktop and mobile environments.
ECMAScript 6 (or ECMAScript 2015) is the newest version of the ECMAScript standard and has remarkably improved parameter handling in JavaScript. We can now use rest parameters, default values and destructuring, among other new features.
PS: This article is mainly translated from Faraz Kelhini’s article (see reference 1) with some of the author’s own understanding added.
Background Introduction
With the arrival of ES6, JavaScript gained many new features that make syntax clearer, more concise, and improve efficiency and reliability, facilitating later extension and maintenance. Although many new features are not yet widely adopted, learning them helps apply ES6 in real projects. Browser support is optimistic, and tools like Babel can transpile ES6 to ES5 for compatibility, so using ES6 in development is worthwhile.
Concept Introduction
Arguments and Parameters are often used to describe function parameters, usually without distinction. For clarity, we define:
Arguments are the actual values passed to a function, similar to actual parameters in other languages and correspond to the
argumentsobject inside a function’s scope.
Parameters are the variable names declared in the function definition, analogous to formal parameters in other languages. In JavaScript, Arguments and Parameters can differ in type (JavaScript is weakly typed) and quantity.
<code>function foo(param1, param2) {
// do something
}
foo(10, 20, 30);
</code>In the example above,
10,
20,
30are Arguments, while
param1and
param2are Parameters.
Spread Operator in Arguments
In ES5, we often used apply() to pass an array to a function, e.g., using Math.max() to find the maximum element of an array because the method does not accept an array directly.
<code>var myArray = [5, 10, 50];
Math.max(myArray); // Error: NaN
Math.max.apply(Math, myArray); // 50
</code>ES6 introduces the spread operator ( ... ), allowing arrays to be expanded into individual arguments without apply() :
<code>var myArray = [5, 10, 50];
Math.max(...myArray); // 50
</code>The spread operator can replace apply() , offering clearer semantics and flexibility, such as using it multiple times in a single call or mixing with regular arguments.
<code>function myFunction() {
for (var i in arguments) {
console.log(arguments[i]);
}
}
var params = [10, 15];
myFunction(5, ...params, 20, ...[25]); // 5 10 15 20 25
</code>It can also be used directly in constructors:
<code>new Date(...[2016, 5, 6]); // Mon Jun 06 2016 00:00:00 GMT-0700 (Pacific Daylight Time)
</code>Rest Operator in Parameters
The rest operator ( ... ) used in a function declaration collects unmatched arguments into an array (the “rest parameter”).
<code>function myFunction(...options) {
return options;
}
myFunction('a', 'b', 'c'); // ["a", "b", "c"]
</code>When no arguments are passed, the rest parameter is an empty array. Using rest parameters simplifies functions with variable numbers of arguments compared to the
argumentsobject, which is not a true array.
<code>function checkSubstrings(string, ...keys) {
for (var key of keys) {
if (string.indexOf(key) === -1) {
return false;
}
}
return true;
}
checkSubstrings('this is a string', 'is', 'this'); // true
</code>ES6 default parameters can only appear after regular parameters and at most one default parameter can be used per function declaration.
Default Parameters
ES5 does not support default parameters; developers often used logical OR or explicit checks, which can mis-handle falsy values like
0or
null. ES6 allows true default values that are applied only when the argument is
undefined.
<code>function foo(param1 = 10, param2 = 10) {
console.log(param1, param2);
}
foo(); // 10 10
foo(0, null); // 0 null
</code>Destructuring Parameters
Destructuring lets you map an object or array directly to variables, improving readability and conciseness. It can be combined with default values and used in function parameters.
<code>function initiateTransfer({
protocol = 'http',
port = 800,
delay = 150,
retries = 10,
timeout = 500,
log = true
}) {
// code to initiate transfer
}
</code>Pass-by-Value vs. Pass-by-Reference
JavaScript always passes arguments by value. For primitive values, a copy is made, so modifications inside the function do not affect the original variable. For objects or arrays, the value is a reference to the memory region, so modifying properties or elements affects the original object.
<code>var a = 5;
function increment(a) {
a = ++a;
console.log(a);
}
increment(a); // 6
console.log(a); // 5
var obj = { bar: 'value' };
function foo(param) {
param.bar = 'new value';
}
console.log(obj.bar); // value
foo(obj);
console.log(obj.bar); // new value
</code>Parameter Validation
Because JavaScript lacks static type declarations, functions can receive any type and number of arguments. To avoid runtime errors from missing or undefined parameters, you can validate arguments early or use default parameters that throw errors when required arguments are absent.
<code>function throwError() {
throw new Error('Missing parameter');
}
function foo(param1 = throwError(), param2 = throwError()) {
// do something
}
foo(10, 20); // ok
foo(10); // Error: Missing parameter
</code>arguments Object
ES6 retained the
argumentsobject, which is not a true array but has a
lengthproperty and index access. It lacks array methods, but you can convert it using
Array.from(arguments)or
Array.prototype.slice.call(arguments). In ES5 non‑strict mode,
arguments.calleeexisted, but it is deprecated in strict mode and ES6.
Conclusion
ES6 brings hundreds of improvements to JavaScript, and developers are increasingly using these new features. This article summarized how ES6 enhances parameter handling, but many other exciting features remain to be explored.
References
How To Use Arguments And Parameters In ECMAScript 6
Optimization killers——Managing arguments
Tencent IMWeb Frontend Team
IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.