Hi, I’m new to JS and I’m learning this new feature called “destructuring an object into an arrow function” but I’ve a problem understanding this code:
When you destructure you use the exact names of the keys in the object. So the destructured function parameter of prop1 and prop2 will use the values of prop1 and prop2 of the objects someObject and anotherObject.
Just try and create a third object like this:
const anotherObject2 = {
prop4: 4,
prop5: 2
}
Then call someArrowFunction(anotherObject2) in the console. It returns undefined. So prop4 and prop5 don’t work because they don’t exactly match the destructured function parameters of prop1 and prop2.
someArrowFunction(someObject). It returns 4 which is correct.
When I do this:
const anotherObject = {
prop1: 4,
prop2: 2
}
then call someArrowFunction(anotherObject) it returns 3 which is correct.
Both of those work because their key names (prop1 and prop2) match exactly what the function parameters ask for: {prop1, prop2}. Because they’re wrapped in { } in the function, it’s like saying “This parameter should be an object with keys named prop1 and prop2”
I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.
You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.
= means assign the value on the right-hand side to the variable name on the left-hand side. This is doing that, but it’s also saying “match this shape object”. You know which keys because you’re literally writing the keys you want to match: if you write something different that isn’t a key on the object then it isn’t going to match.