Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript Function Returns Multiple Values as Object in ES6

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?

like image 431
user3256451 Avatar asked Jun 18 '17 07:06

user3256451


2 Answers

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.

like image 133
Prateek Pandey Avatar answered Sep 21 '22 21:09

Prateek Pandey


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 }
like image 33
Nina Scholz Avatar answered Sep 20 '22 21:09

Nina Scholz