Easiest way to check if string is null or empty
I've got this code that checks for the empty or null string. It's working in testing.
eitherStringEmpty= (email, password) ->
emailEmpty = not email? or email is ''
passwordEmpty = not password? or password is ''
eitherEmpty = emailEmpty || passwordEmpty
test1 = eitherStringEmpty "A", "B" # expect false
test2 = eitherStringEmpty "", "b" # expect true
test3 = eitherStringEmpty "", "" # expect true
alert "test1: #{test1} test2: #{test2} test3: #{test3}"
What I'm wondering is if there's a better way than not email? or email is ''
. Can I do the equivalent of C# string.IsNullOrEmpty(arg)
in CoffeeScript with a single call? I could always define a function for it (like I did) but I'm wondering if there's something in the language that I'm missing.
Yup:
passwordNotEmpty = not not password
or shorter:
passwordNotEmpty = !!password
It isn't entirely equivalent, but email?.length
will only be truthy if email
is non-null and has a non-zero .length
property. If you not
this value the result should behave as you want for both strings and arrays.
If email
is null
or doesn't have a .length
, then email?.length
will evaluate to null
, which is falsey. If it does have a .length
then this value will evaluate to its length, which will be falsey if it's empty.
Your function could be implemented as:
eitherStringEmpty = (email, password) ->
not (email?.length and password?.length)