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?
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?
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.
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