3

I am new to React. Recently I came across an application wherein some function had the definition as:

async function (a, b) => {//body} which is quite understandable. But also in the same apllication some functions had the structure as async function ({a,b}) => {//body}. What is the difference between defining function between the above two methods?

3 Answers3

3

The second example is destructuring the function arguments. It basically provides a shorter syntax for extracting an object key's value without the dot notation mess

Let's say you have an object

const myObject = { x: 1, y: 2 };

So, when you pass myObject to the function, you can call the variables without the dot notation. This makes the code easier to read.

function myFunction({ x, y }) {
//Here you can use directly x instead of myObject.x
}

You can read more about destructuring here

Ozgur Sar
  • 1,598
  • 2
  • 6
  • 18
2

in the first function your parameter are 2 different variables

, in the second function they are parameters of the object you are passing

like

let Cat = {
name:"catty",
color:"gray"
}

secound example  you pass the whole object like this

function ( Cat ) {}


function ( { name , color } )  {

/// here you can use name and color as "catty" and "gray"

}

if you use the first expample you would have to specify the parameters like this

function (Cat.name , Cat.color) {



}


the word async refers to waiting this function to call

Dolev Dublon
  • 378
  • 1
  • 2
  • 14
1

In the first case, there are 2 arguments passed into the function, in the second the first argument passed into the function is an object which is being destructured.

const obj = { a: 1, b: 2 }

async function foo({ a, b }) => {
  a; // 1
  b; // 2
}

foo(obj);
Sergey
  • 822
  • 6
  • 17