prints two values without destructuring

Viewed 89

i'm trying to learn javascript destructuring and got stuck, did not find similar to this so im asking if somebody could enlighten me. I have two kind of question 1: here i have destructure in argument ( is it destructure?) and above i have function without destructure it prints {size: 7, radius: 4}25, my question here is why it prints 25 also ? like now it has printed both 'radius's' shoudnt it print just one 'radius(4)' ?

function drawChart(size = 'big', radius = 25 ) {
  console.log(size, radius);
} 
 
drawChart({size:7, radius:4} );

2: Now i have put curly braces inside function and there is also curly braces inside argument (which one is destructuring (object destructuring?), both or just above ?), it prints '7 4', now here is not 25, why ?

function drawChart({ size = 'big', radius = 25 } ) {
  console.log(size, radius);
} 
 
drawChart({size:7, radius:4} );

if somebody could clarify this i would appreciate it

3 Answers

For your first function, here is what's happening:-

Both size and radius function parameters are primtives of type string and number with default value of big and 25.

Now you call drawChart({size:7, radius:4}) which essentially sets your function parameter size equivalent to {size:7,radius:4} and radius is not set to anything but holds the default value of 25.

So the output is

{
  "size": 7,
  "radius": 4
} 25

For your second function :- You have actually used destructuring here for your function parameters. You pass in only one parameter here and that's the object {size:7, radius:4}. So at runtime, size with default value of big gets set to 7 and radius with default value of 25 gets set to 4.

So the output is

7 4

I hope this made sense.

In example 1, drawChart({size:7, radius:4}) passes a single object argument to the drawChart() function. However, you have declared drawChart() to accept 2 arguments. This means that in the function, the size parameter will be equal to {size:7, radius:4} while the radius parameter takes on its default value of 25.

In example 2, you are defining drawChart() to only take 1 argument that is an object, and from that object you are using destructuring to get the size and radius attributes.

To get example 1 to work like example 2 without using curly braces, you can have drawChart() accept a single object and then access that object's attributes.

function drawChart(data) {
  console.log(data.size || 'big', data.radius || '25');
} 
 
drawChart({size:7, radius:4});
drawChart({size:7});
drawChart({radius:4});

I think what you are looking for is like so:

function drawChart(props) {
  const { size, radius } = props;
  console.log(size, radius);
} 
Related