Steerpike
Steerpike

Reputation: 1863

Returning multiple values from a JavaScript function

I'm a newcomer to JavaScript and I'm sure this is very straightforward: I wish to set a number of values based upon a single input in a switch statement. I know in Java I would use getters/setters and or pass the values into an array and pick the relevant field based on its index.

let custCode;
let loyaltyCode;
let id;

const setCustomerCodes = () => {
  switch (customerType) {
    case "NEW":
      (custCode = "19202"), (loyaltyCode = "X78"), (id = "396550");
      break;
    case "CURRENT":
      (custCode = "93893"), (loyaltyCode = "X89"), (id = "396438"); 
      break;
    case "LOYAL":
      (custCode = "76353"), (loyaltyCode = "X90"), (id = "396440"); 
      break;
    default:
      (custCode = "02902"), (loyaltyCode = "X80"), (id = "396637"); 
      break;
  }
  return //all values as an object?;
};

module.exports = {
   //export the values to use in separate file 
};

I then just want to use the value of each field in a separate JS file. I know this is very basic; easier when I can get my head around debugging in VS Code

Upvotes: 0

Views: 164

Answers (2)

Hossein Mohammadi
Hossein Mohammadi

Reputation: 1473

I think you could return an object.

const setCustomerCodes = () => {
  switch (customerType) {
    case "NEW":
      return {custCode: "19202", loyaltyCode: "X78", id: "396550"}
    case "CURRENT":
      return {custCode: "93893", loyaltyCode: "X89", id: "396438"}; 
    case "LOYAL":
      return {custCode: "76353", loyaltyCode: "X90", id: "396440"}; 
    default:
      return {custCode: "02902", loyaltyCode: "X80", id: "396637"}; 
  }
};
const {
  custCode,
  loyaltyCode,
  id,
  } = setCustomerCodes()
module.exports = {
  custCode,
  loyaltyCode,
  id,
};

Upvotes: 0

ATD
ATD

Reputation: 1364

Here is one possible solution:

let custCode;
let loyaltyCode;
let id;

const setCustomerCodes = (customerType) => {
  switch (customerType) {
    case "NEW":
      (custCode = "19202"), (loyaltyCode = "X78"), (id = "396550");
      break;
    case "CURRENT":
      (custCode = "93893"), (loyaltyCode = "X89"), (id = "396438"); 
      break;
    case "LOYAL":
      (custCode = "76353"), (loyaltyCode = "X90"), (id = "396440"); 
      break;
    default:
      (custCode = "02902"), (loyaltyCode = "X80"), (id = "396637"); 
      break;
  }
  return {custCode, loyaltyCode, id}
};

let x = setCustomerCodes("NEW");
console.log(x);
console.log(x.custCode);
console.log(x.loyaltyCode);
console.log(x.id);

As @VLAZ suggests, you simply return all of the values in {} as a single object. The x variable I have defined can then be used to get to the individual values (as shown in the separate console.log(...) entries.

Note that you do need to pass in a value for customerType, so I've included that as a parameter

Upvotes: 1

Related Questions