11
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?

1
  • Are you using babel transpiler or not ? Which browser with version you are testing on ? Commented Jun 18, 2017 at 7:41

3 Answers 3

21

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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 }

Comments

0

Use like this

function function_name()
{
    var a=1;
    var b=2;

    return [a, b] 
}

let [p1, q1] = function_name()

return multiple values as array

1 Comment

Your answer doesn't explain the question from the OP at all. Also, in general providing a code example is good, but it should be a) as simple as possible and b) the code example should be accompanied by an explanation as to why your example works and that from the OP doesn't work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.