Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why value from variable "y" is 5? not 7?

first of all sorry for my bad english

so, this is my code:

let x = 5
const {x: y=7} = {x}

console.log(y) // output is 5

but why 5? is not 7?

like image 445
Zulfikar Ahmad Avatar asked Jan 20 '26 00:01

Zulfikar Ahmad


1 Answers

{x} is shorthand for {x: x}. Since the value of x is 5, this is equivalent to {x: 5}.

That means your code is equivalent to

const {x: y=7} = {x: 5}

This sets y to the value of the x property in {x: 5}. If there were no property, it would use the default value of 7; but since the property does exist, its value is used, so it sets y to 5.

Compare with

let a = 5;
const {x: y=7} = {a}

This will set y to 7 because there's no x property in the object.

like image 146
Barmar Avatar answered Jan 21 '26 13:01

Barmar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!