-2

I don't understand the difference between these two functions:

function animal({ cat }){
  return cat 
}

function animal(cat){
  return cat 
}

why use one over the other? Is there an advantage?

Sushanth --
  • 55,259
  • 9
  • 66
  • 105
olafsadventures
  • 151
  • 1
  • 10
  • Did you try running the code? They don't do the same thing... – Jared Smith Nov 10 '18 at 03:13
  • 4
    The first is using [Destructuring assignment](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment) and the other is returning the full cat object. – Nick Parsons Nov 10 '18 at 03:14

2 Answers2

0

The first function will return the property cat from the object which is passed in as it is using destructuring assignment. The second will return the full object cat which is the objected that was passed in.

For example, the first function is equivalent to:

function animal(catObj){
  return catObj.cat; 
}

Meaning that when you call animal() you pass through an object which has the property cat within it.

eg:

const myCatObj = {
  cat: true,
  dog: false,
  name: "Meow"
}

animal(myCatObj); // retruns true

So, if we're looking at the first function, this will extract the cat property and return true.

Your second function will simply just return the entire object passed into the function. So if we passed through myCatObj we would get the same contents within myCatObj as an output.

So, to answer your question, both are used to perform different sorts of functions, so they each have their own advantages in certain scenarios.

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
-1

calling those two functions

animal({cat:9}); returns 9

animal(9); returns undefined since the number 9 does not have a cat property (everything is an object in js)

we use the 1st function when we want to know about the cat property of an object

we use the second one when we want to call an object directly

Aditya Shankar
  • 702
  • 6
  • 12