JavaScript function return 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 the error message p1

, q1

how undefined

? However, the code below gives the expected results:

 var o = {p: 42, q: true};
 var {p, q} = o;

 console.log(p); // 42
 console.log(q); // true

      

Can anyone explain the difference between the two code examples?

+3


source to share


2 answers


You get the desired result because function_name () returns an object that has two variables a and b that have some value.

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

      

here is return {a, b}

equivalently return {a: a, b: b}

equivalentreturn {a: 1, b: 2}



To get the exact value, you need to update the calling method signature:

let {a, b} = function_name()

      

Note . It is bad practice to use the variable name a or b. You must use valid names.

+8


source


This is a destructuring that uses the keys in curly braces to get values ​​with the same job key. Your function reconfigures the object

{ a: 1, b: 2 }

      

and then you want to get properties named p1

and p2

. Obviously, there are no keys with these names in this object, and therefore there is no property as a result.

{ a: 1, b: 2 } => get { p1 and p2 } => {}

      



Working example

{ p: 42, q: true } => get { p and q } => { p: 42, q: true }

      

With a different property

{ p: 42, q: true, foo: 42 } => get { p and q } => { p: 42, q: true }

      

+5


source







All Articles