function function_name()
{
var a=1;
var b=2;
return {a, b}
}
let {p1, q1} = function_name()
Why do I get an error message about the values of p1
, q1
as undefined
? However, the below code gives the expected results:
var o = {p: 42, q: true};
var {p, q} = o;
console.log(p); // 42
console.log(q); // true
Can any one please explain the difference between the two code examples?
You are getting desired output because function_name() is returning an object that is having two variables a and b having some value.
function function_name()
{
var a=1;var b=2;
return {a,b}
}
here return {a, b}
is equivalent to return {a: a, b: b}
is equivalent to return {a: 1, b: 2}
To get the exact value you need to update your calling method signature to:
let {a, b} = function_name()
Note: It is not a good practice to use a or b as variable name. You should use valid names.
It is a destructuring, which uses the keys in the curly bracket for getting the values with the same key of the assignment. Your function retuns an object
{ a: 1, b: 2 }
and then you want to get the properties with the names p1
and p2
. Obviously there are no keys with this names in the object and therefor no property in the result.
{ a: 1, b: 2 } => get { p1 and p2 } => {}
Working example
{ p: 42, q: true } => get { p and q } => { p: 42, q: true }
With another property
{ p: 42, q: true, foo: 42 } => get { p and q } => { p: 42, q: true }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With