Reputation: 3243
I am getting type error string is null,
i am checking string like this:
if (typeof s != 'undefined' || s.length){
var j = JSON.stringify(
s.split(',').reduce(function(m,v) {
var t = v.split(':');
m[t[0]] = t[1];
return m;
}, {})
);
}
But still it shows type error,
tell me how to not run this function on null
?
Upvotes: 1
Views: 670
Reputation: 21752
first of all null
and undefined
are two distinct values, so for the short circuiting to work you need to test both undefined and null you wouldn't need the typeof function for that you could simply do
if(s != undefined && s != null && s.length)
that changes the logic in your code because you are testing with ||
but that will always fail in your case (it will only be used if the type of s is undefined)
however since both null and undefined are falsy values. That is used as a boolean expression they both evaluate to false you can simply do
if(s && s.length){
}
There's quite a few falsy values in JS
The last one is the only truely false value so if you do value === false
only the last of those five will evaluate to true where as all of them will evaluate to false in a condition
Any string that has a length is also a truthy value there's one somewhat surprising value that evaluates to true which is "false"
and since all strings with a length > 0 will evaluate to true the only way the above if will fail is if there's no length property. That's is if it's not a string (or an array or any other type with a length property).
So you could either remove the test of length altogether
if(s){
}
or make it explicit that you are testing for a string
if(s && typeof s === "string"){
}
Upvotes: 1
Reputation: 17380
To check for null string you should probably try this:
if(s)
{}
as far as for empty string, checking the length the way you are should be fine and probably faster than ===
or ==
.
Upvotes: 1