惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

G
Google Developers Blog
S
Schneier on Security
The Hacker News
The Hacker News
P
Proofpoint News Feed
Spread Privacy
Spread Privacy
L
LINUX DO - 热门话题
L
Lohrmann on Cybersecurity
I
Intezer
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Schneier on Security
Schneier on Security
Security Latest
Security Latest
AWS News Blog
AWS News Blog
B
Blog RSS Feed
Microsoft Security Blog
Microsoft Security Blog
有赞技术团队
有赞技术团队
博客园 - 叶小钗
The Last Watchdog
The Last Watchdog
O
OpenAI News
月光博客
月光博客
Hacker News: Ask HN
Hacker News: Ask HN
阮一峰的网络日志
阮一峰的网络日志
S
Security @ Cisco Blogs
Google Online Security Blog
Google Online Security Blog
云风的 BLOG
云风的 BLOG
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Latest news
Latest news
P
Palo Alto Networks Blog
Last Week in AI
Last Week in AI
M
MIT News - Artificial intelligence
Google DeepMind News
Google DeepMind News
P
Proofpoint News Feed
C
CERT Recently Published Vulnerability Notes
Apple Machine Learning Research
Apple Machine Learning Research
U
Unit 42
PCI Perspectives
PCI Perspectives
博客园 - 聂微东
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Forbes - Security
Forbes - Security
H
Heimdal Security Blog
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
T
Troy Hunt's Blog
博客园 - 三生石上(FineUI控件)
Application and Cybersecurity Blog
Application and Cybersecurity Blog
罗磊的独立博客
WordPress大学
WordPress大学
D
Darknet – Hacking Tools, Hacker News & Cyber Security

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback()
Let's Master JavaScript Function Parameters
Dmitri Pavlutin · 2019-09-17 · via Dmitri Pavlutin Blog

A function is a cohesive piece of code coupled to perform a specific task. The function accesses the outer world using its parameters.

To write concise and efficient JavaScript code, you have to master the function parameters.

In this post, I will explain with interesting examples of all the features that JavaScript has to efficiently work with function parameters.

1. Function parameters

A JavaScript function can have any number of parameters.

Let's define functions that have 0, 1 and 2 parameters:


// 0 parameters

function zero() {

return 0;

}

// 1 parameter

function identity(param) {

return param;

}

// 2 parameters

function sum(param1, param2) {

return param1 + param2;

}

zero(); // => 0

identity(1); // => 1

sum(1, 2); // => 3


The 3 functions above were called with the same number of arguments as the number of parameters.

But you can call a function with fewer arguments than the number of parameters. JavaScript does not generate any errors in such a case.

However, the parameters that have no argument on invocation are initialized with undefined value.

For example, let's call the function sum() (which has 2 parameters) with just one argument:


function sum(param1, param2) {

console.log(param1); // 1

console.log(param2); // undefined

return param1 + param2;

}

sum(1); // => NaN


The function is called only with one argument: sum(1). While param1 has the value 1, the second parameter param2 is initialized with undefined.

param1 + param2 is evaluated as 1 + undefined, which results in NaN.

If necessary, you can always verify if the parameter is undefined and provide a default value. Let's make the param2 default to 0:


function sum(param1, param2) {

if (param2 === undefined) {

param2 = 0;

}

return param1 + param2;

}

sum(1); // => 1


But there is a better way to set default values. Let's see how it works in the next section.

2. Default parameters

The ES2015 default parameters feature allows initializing parameters with defaults. It's a better and more concise way than the one presented above.

Let's make param2 default to value 0 using ES2015 default parameters feature:


function sum(param1, param2 = 0) {

console.log(param2); // => 0

return param1 + param2;

}

sum(1); // => 1

sum(1, undefined); // => 1


In the function signature there's now param2 = 0, which makes param2 default to 0 if it doesn't get any value.

Now if the function is called with just one argument: sum(1), the second parameter param2 is initialized with 0.

Note that if you set undefined as the second argument sum(1, undefined), the param2 is initialized with 0 too.

3. Parameter destructuring

What I especially like in the JavaScript function parameters is the ability to destructure. You can destructure inline the parameter's objects or arrays.

This feature makes it useful to extract just a few properties from the parameter object:


function greet({ name }) {

return `Hello, ${name}!`;

}

const person = { name: 'John Smith' };

greet(person); // => 'Hello, John Smith!'


{ name } is a parameter on which was applied to the destructuring of an object.

You can easily combine the default parameters with destructuring:


function greetWithDefault({ name = 'Unknown' } = {}) {

return `Hello, ${name}!`;

}

greetWithDefault(); // => 'Hello, Unknown!'


{ name = 'Unknown' } = {} defaults to an empty object.

You can use all the power of combining the different types of destructuring. For example, let's use the object and array destructuring on the same parameter:


function greeFirstPerson([{ name }]) {

return `Hello, ${name}!`;

}

const persons = [{ name: 'John Smith' }, { name: 'Jane Doe'}];

greeFirstPerson(persons); // => 'Hello, John Smith!'


The destructuring of parameter [{ name }] is more complex. It extracts the first item of the array, then reads from this item the name property.

4. arguments object

Another nice feature of JavaScript functions is the ability to call the same function with a variable number of arguments.

If you do so, it makes sense to use a special object arguments, which holds all the inocation arguments in an array-like object.

For example, let's sum the arguments of a function:


function sumArgs() {

console.log(arguments); // { 0: 5, 1: 6, length: 2 }

let sum = 0;

for (let i = 0; i < arguments.length; i++) {

sum += arguments[i];

}

return sum;

}

sumArgs(5, 6); // => 11


arguments contains the arguments the function was called with.

arguments is an array-like object, so you cannot use all the fancy array methods on it.

Another difficulty is that each function scope defines it's own arguments object. Thus you might need an additional variable to access the outer function scope arguments:


function outerFunction() {

const outerArguments = arguments;

return function innerFunction() {

// outFunction arguments

outerArguments[0];

};

}


4.1 Arrow functions case

There's a special case: arguments is not available inside the arrow functions.


const sumArgs = () => {

console.log(arguments);

return 0;

};

// throws: "Uncaught ReferenceError: arguments is not defined"

sumArgs();


arguments is not defined inside the arrow function.

But this is not a big problem. You can use more efficiently the rest parameters to access all the arguments inside the arrow function. Let's see how to do that in the next section.

5. Rest parameters

The ES2015 rest parameter lets you collect all the arguments of the function call into an array.

Let's use the rest parameters to sum the arguments:


function sumArgs(...numbers) {

console.log(numbers); // [5, 6]

return numbers.reduce((sum, number) => sum + number);

}

sumArgs(5, 6); // => 11


...numbers is a rest parameter that holds the arguments in an array [5, 6]. Since numbers is an array, you can easily use all the fancy array methods on it (contrary to arguments that is an array-like object).

While the arguments object is not available inside the arrow functions, the rest parameters work without problem here:


const sumArgs = (...numbers) => {

console.log(numbers); // [5, 6]

return numbers.reduce((sum, number) => sum + number);

}

sumArgs(5, 6); // => 11


If not all the arguments should be collected inside the rest parameter, you can freely combine regular parameters with the rest parameter.


function multiplyAndSumArgs(multiplier, ...numbers) {

console.log(multiplier); // 2

console.log(numbers); // [5, 6]

const sumArgs = numbers.reduce((sum, number) => sum + number);

return multiplier * sumArgs;

}

multiplyAndSumArgs(2, 5, 6); // => 22


multiplier is a regular parameter that gets the first argument's value. Then the rest parameter ...numbers receives the rest of the arguments.

Note that you can have up to one rest parameter per function. As well as the rest parameter must be positioned last in the function parameters list.

6. Conclusion

Beyond the basic usage, JavaScript offers lots of useful features when working with function parameters.

You can easily default a parameter when it's missing.

All the power of JavaScript destructuring can be applied to parameters. You can even combine destructuring with default parameters.

arguments is a special array-like object that holds all the arguments the function was invoked with.

As a better alternative to arguments, you can use the rest parameters feature. It holds as well the arguments list, however, it stores them into an array.

Plus you can use regular parameters with rest parameter, the latter, however, must always be last in the params list.

What parameters feature do you use the most? Feel free to write a comment below!