26

I'm having problems finding out what's wrong with the code below. I have consulted how to use typeof and switch cases, but I'm lost at this point. Thanks in advance for your advices.

// Write a function that uses switch statements on the
// type of value. If it is a string, return 'str'. If it
// is a number, return 'num'. If it is an object, return
// 'obj'. If it is anything else, return 'other'.
function detectType(value) {
  switch (typeof value) {
    case string:
      return "str";
    case number:
      return "num";
    default:
      return "other";
  }
}

------------- Update -----------------------------------

Turns out the problem comes from my mistake (or rather oversight) of not following the instructions properly. Thanks again for your help and comments!

Community
  • 1
  • 1
stanigator
  • 10,768
  • 34
  • 94
  • 129

4 Answers4

38

typeof returns a string, so it should be

function detectType(value) {
  switch (typeof value) {
    case 'string':
      return "str";
    case 'number':
      return "num";
    default:
      return "other";
  }
}
qiao
  • 17,941
  • 6
  • 57
  • 46
  • That brings me another question. When should I use single quotations and when should I use double quotations? – stanigator Jan 06 '12 at 06:45
  • 1
    It really doesn't matter, I typed single quotes in the above example only because it's my personal preference. For more details about the question, see http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript – qiao Jan 06 '12 at 06:48
3

This is the code that will work. I'm going through the codeacademy.com coures also. The issue was with typeOf having mixed casing. It's case sensitive and should be all lowercase: typeof

function detectType(value) {
  switch(typeof value){
    case "string":
      return "str";
    case "number":
      return "num";
    case "object":
      return "obj";
    default:
      return "other";
  }
}
d48
  • 702
  • 7
  • 15
1

typeof returns a string so you should encase your switch cases between single quotes.


function detectType(value) {
  switch (typeof value) {
    case 'string': // string should me 'string'
      return "string";
    case 'number':
      return "number";
    default:
      return "other";
  }
}

1

This is the code the will work for you:

function detectType(value) {
  switch (typeof value) {
  case "string":
     return "str";
  case "number":
     return "num";
  default:
     return "other";
  }
}
Ido Green
  • 2,795
  • 1
  • 17
  • 26