0

Say I wanted a function that checked whether or not a variable is a string, the interwebs advised me as follows:

function is_string(s) { return typeof s === 'string'; }

but I can't think of any scenario where "typeof s" could return "string" without s actually being a string.

Is there any reason for that === operator instead of ==?

Reason being, I want to check types in a switch statement, AFAIK, the switch statement uses the loose comparison operator. Since I'm only looking for known types and don't need to check for undefined, it should be fine, right?

user81993
  • 6,167
  • 6
  • 32
  • 64
  • Yes, you should be fine in this case. typeof wouldn't return any other thing that could accidentally be converted to the string 'string', so it's safe to use in a switch. But also check Mahi's reference, because it's always good to know about any exceptions. – GolezTrol Nov 17 '16 at 16:27
  • It will return `true` or `false`, not `string`. Returns true if it's a string, and false if not. What's the question? Strict or non strict comparison operator doesn't matter here, `typeof` would return an string – Marcos Pérez Gude Nov 17 '16 at 16:27
  • Btw, `switch` uses strict equality. – Bergi Nov 17 '16 at 17:39

0 Answers0