Piotr Mirosz
Piotr Mirosz

Reputation: 866

JS passing value and choose return var

It is possible to return only 1 value from function witch returning 5 values? Example include only 2 values:

   function checkNum(x){
    if(x>0){
       if(x>59){
           return "green" , "pass";
       }
       else{
           return "red" , "try again";
       }
    }
    else{
        return "yellow","play the game";
    }
    }

    console.log(checkNum(33));

As you see it only return 2nd val witch is try again...

How get something like that: Sorry "try again" you are "red"!!

or i have to copy each function and change names for each return state??

Please give a clue.

Upvotes: 1

Views: 441

Answers (2)

MaieonBrix
MaieonBrix

Reputation: 1624

There are multiple ways to do what you have in mind, you can for example create a string and return it like so :

   function checkNum(x){
    if(x>0){
      ...
       else{
           return 'Try again, ' + 'you are red !!!'
       }
    }
    ...
    }

Also, keep in mind that you can only return one value from a function, and when you are returning like what you did a lot of values or any other javascript expression, only the most right-handed expression will be the return value.

function aLotOfReturn() {
    return 'one', 1 + 2, {}, 'four';
}
aLotOfReturn() // returns 'four'

if you want to return multiple values you can use different type of primitives that fits those needs like : key-value object or array

like so

function returnMultipleColors() {
    return ['blue', 'red', 'yellow'];
}

let colors = returnMultipleColors();


You have now an array of colors, you can choose to iterate over it using the .forEach method or many more to do whatever you want with each value.

UPDATE : here is an article illustrating some useful javascript array and object methods : https://codeburst.io/useful-javascript-array-and-object-methods-6c7971d93230

Upvotes: 2

Andy Gaskell
Andy Gaskell

Reputation: 31761

Returning an array is probably what you want:

function checkNum(x) {
  if (x > 0) {
    if (x > 59) {
      return ["green", "pass"];
    } else {
      return ["red", "try again"];
    }
  } else {
    return ["yellow", "play the game"];
  }
}

const [color, message] = checkNum(33);
console.log(`${color} - ${message}`);

You could also return an object if you prefer:

function checkNum(x) {
  if (x > 0) {
    if (x > 59) {
      return { color: "green" , message: "pass" };
    } else {
      return { color: "red" , message: "try again" };
    }
  } else {
    return { color: "yellow", message: "play the game" };
  }
}

const { color, message } = checkNum(33);
console.log(`${color} - ${message}`);

Upvotes: 2

Related Questions