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.
Instead of the accepted answer
passwordNotEmpty = !!password
you can useIt gives the same result (the difference only in syntax).
In the first column is a value, in the second is the result of
if value
:It isn't entirely equivalent, but
email?.length
will only be truthy ifemail
is non-null and has a non-zero.length
property. If younot
this value the result should behave as you want for both strings and arrays.If
email
isnull
or doesn't have a.length
, thenemail?.length
will evaluate tonull
, 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:
Yup:
or shorter:
You can use the coffeescript or= operation
I think the question mark is the easiest way to call a function on a thing if the thing exists.
for example
you want to get the color, but only if the car exists...
coffeescript:
translates to javascript:
it is called the existential operator http://coffeescript.org/documentation/docs/grammar.html#section-63
This is a case where "truthiness" comes in handy. You don't even need to define a function for that:
Why does it work?