user10588397
user10588397

Reputation:

How to use a specific variable out of three returned variables?

I have got three variables (x,y,z) and I have returned them all. I want to use a specific variable out of the three instead of just using the newest one.

This is to test what I can do for my loading screen which I mentioned in a previous question. I have tried to put the variable in the void to no avail. I have researched this and I haven't found anything.

function inputs(){
    var x = 19;
    var y = 20;
    var z = 21;
    return x, y, z;
}

function output(){
    console.log(inputs(x));
}

output();

My expected result is that I can log x to my console. My actual result is that it says undefined.

Upvotes: 1

Views: 42

Answers (4)

Sankalpa Timilsina
Sankalpa Timilsina

Reputation: 341

You cannot return comma separated values like this:

return x, y, z;

Instead what you can do is return an object:

function inputs(){
    var x = 19;
    var y = 20;
    var z = 21;
    return {x: x, y: y, z: z};
}

function output(){
   console.log(inputs().x)
}

output()

Hope you understand.

Upvotes: 0

Aadit M Shah
Aadit M Shah

Reputation: 74234

In ES6 you can do this:

function inputs() {
    var x = 19;
    var y = 20;
    var z = 21;
    return {x, y, z};
}

function output() {
    console.log(inputs().x);
}

output();

Hope that helps.

Upvotes: 1

Code Maniac
Code Maniac

Reputation: 37755

Your input(x) here x is undefined so.

And x,y,z will also always return z. Read more about comma operator

So what you're trying to achieve can be done like this with object.

You can do it like this

function inputs(input){
    let obj =
    { x : 19,
      y : 20,
      z : 21 }
    return obj[input]
}

function output(){
    console.log(inputs('x'));
}

output();

Upvotes: 1

Brenden
Brenden

Reputation: 329

Returning x, y, z actually only returns z. What you want is an Object, like let a = {x, y, z}, which you can then access z from using a.z.

Upvotes: 0

Related Questions