javascript - Is it ok to do a type-converting comparison when checking if something is a string? -
since typeof somevariable === string
not return true strings instantiated new string()
, ok this:
if(typeof somevariable == 'string') { // }
to make sure comparison catch cases well, or such comparison have unintended side effects?
since typeof somevariable === string not return true strings instantiated new string(), ok this:
it's okay, won't give true
string objects, it'll still false
. it's not ==
vs. ===
matters, it's you're checking.
if want reliably check both string primitives , string objects, then:
if (object.prototype.tostring.call(somevariable) === "[object string]")
...is how that. works because if somevariable
string object, that's string object.prototype.tostring
guaranteed return it. if somevariable
string primitive, either using thisarg
in function#call
(loose mode) or object.prototype.tostring
function (strict mode) coerce string object before figuring out is. either way, "[object string]"
.
more (on blog): say what?
Comments
Post a Comment