The worm
The worm

Reputation: 5888

Returning correct value from factory

Trying to create a factory in JavaScript, when I pass in a value to the factory I want it to return the correct string instead of the integer.

function Factory(amount){
  switch (amount) {
    case amount == 1:
      return "one "
      break;
    case amount == 2:
      return "two "
      break;
    case amount > 2:
      return "more than two "
      break;
  }
  return amount;
}

var per1 = Factory(1);
console.log(per1, 'per1');
var per2 = Factory(2);
var per3 = Factory(3);

But when I log out per1 I get the value: 1 instead of 'one '.

What have I not done quite right?

Upvotes: 2

Views: 46

Answers (3)

Ali Yousuf
Ali Yousuf

Reputation: 702

Switch case works on values, instead of true/false

function Factory(amount){
  switch (amount) {
    case 0:
      return "zero "
    case 1:
      return "one "
    case 2:
      return "two "
    default:
      return "more than two "
  }
}

You also don't need to break since you already have return.

The default case handles the rest of the cases if not mentioned above. So you also don't need to return amount as a fallback.

Upvotes: 3

Akshay
Akshay

Reputation: 805

try this

function Factory(amount){
  switch (amount) {
    case 1:
      return "one "
      break;
    case 2:
      return "two "
      break;

  }
  return amount;
}



console.log(Factory(1))
//output "one"

Upvotes: 0

subash
subash

Reputation: 3115

      function Factory(amount){
          switch (amount) {
            case 1:
              return "one "

            case 2:
              return "two "

            default:
              return "more than two "

        }
    }

change you case like this

Upvotes: 1

Related Questions