I've been working with the JavaScript learning modules found in CodeAcademy 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?
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?
Share Improve this question asked Jan 4, 2012 at 21:23 AlexAlex 3772 gold badges4 silver badges15 bronze badges 6 | Show 1 more comment3 Answers
Reset to default 7You need to use the typeof
operator:
var value = true;
switch (typeof value) {
case 'string':
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;
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"
switch( typeof value ) {case "string": ... case "number": ... }
– Esailija Commented Jan 4, 2012 at 21:25typeof
? – PeeHaa Commented Jan 4, 2012 at 21:26===
. – Matt Ball Commented Jan 4, 2012 at 21:29==
operator. Because there's no type casting/conversion involved using===
Hence:("1" === 1)
returns false. – Richard A Commented Jan 4, 2012 at 21:35