user13963926
user13963926

Reputation:

ES6 Destructuring in Function

I am trying to learn Destructuring in Javascript introduced with ES6. While following a medium post I came across this code :

function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } }) {
    console.log('Hello, ' + name);
    console.log('Your Maths score is ' + maths);
    console.log('Your English score is ' + english);
    console.log('Your Science score is ' + science);
}

I know this is a way of Destructuring but how do i pass arguments while calling this function? I have tried calling it like

displaySummary({'John Doe',{1,2,3}});

But got an error something like Uncaught SyntaxError: Unexpected Token ','

How do we do this?

Upvotes: 1

Views: 107

Answers (2)

Yves Kipondo
Yves Kipondo

Reputation: 5633

Argument of the function displaySummary is not a valid Object

displaySummary({'John Doe',{1,2,3}});

the function definition expect to receive an object which has this shape

{ 
    name: "John Doe", 
    scores: { 
        maths = 0, 
        english = 0, 
        science = 0 
    } 
}

But in your call you pass an object which has no keys

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

The top level of the parameter list has no commas, so you need to pass a single argument, which has the structure of:

{ name, scores: { maths = 0, english = 0, science = 0 } }

except with :s instead of =s. So:

function displaySummary({ name, scores: { maths = 0, english = 0, science = 0 } }) {
    console.log('Hello, ' + name);
    console.log('Your Maths score is ' + maths);
    console.log('Your English score is ' + english);
    console.log('Your Science score is ' + science);
}


displaySummary({ name: 'bob', scores: { maths: 95 }});

Upvotes: 2

Related Questions