Alex
Alex

Reputation: 377

JavaScript function that uses switch statement on the type of value

I've been working with the JavaScript learning modules found in CodeAcademy.com and find myself unredeemed in chapter 4, module 8 (switch - control flow statements)

Please see below for example request:

// 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'.
// compare with the value in each case using ===

and this is what I was able to code:

function StringTypeOf(value) {
var value = true
switch (true) {
 case string === 'string': 
   return "str"; 
   break;
 case number === 'number':
   return "num"; 
   break;
 case object === 'object':
   return "obj"; 
   break;
 default: return "other";
 }
  return value;
}

Can someone please hint or tell me what is missing here?

Upvotes: 3

Views: 16675

Answers (3)

sam
sam

Reputation: 71

function detectType(value) {
  switch (typeof value){
    case 'string':
      return 'str';

    case 'number':
      return 'num';

    case 'object':
      return 'obj';

    default:
      return 'other';
  }
}

you could left out the break; in this case, because is optional after return;

Upvotes: 7

maerics
maerics

Reputation: 156552

Read the question again - "write a function that uses switch statements on the type of the value". You're missing anything about the type of the value, try using the typeof operator.

typeof "foo" // => "string"
typeof 123 // => "number"
typeof {} // => "object"

Upvotes: 3

Matt H
Matt H

Reputation: 6530

You need to use the typeof operator:

var value = true;
switch (typeof value) {
 case 'string': 

Upvotes: 7

Related Questions