JavaScript Function Returns Multiple Values as Object in ES6

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 }