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?
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?
{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.
note : equals assignment have a left to right operation in other words... the left side takes greater precedence over the right and overrides the any value on the left
const{ x = y } = {x = 5}
x........ maps to..........x
y......... maps to..........5 (overriding the previous y value)
Also........... You can take it this way
what you simply wrote was
y=7
y=5
y=5 came last so it replaced the previous value