Having trouble checking for null condition in coffee script - function

I have a coffee script with the following
#update_states = (countryElt, stateElt, callbackFn) ->
…
if callbackFn != null
callbackFn()
The problem is, even when there is no “callbackFn” argument passed to the function, the “if” block is getting executed. What is the proper way to check if the argument is not null (i.e. is a function passed to the function)?

Code if callbackFn != null is converted to if(callbackFn !== null). If You don't pass the callbackFn argument, callbackFn = undefined. undefined !== null.
Correct way to do this in coffeescript is:
if callbackFn? then callbackFn()
Read more about existential operators

Related

What is the technical term for a programming language's operator evaluation order?

Several procedures such as array destructuring in JavaScript or collection manipulation in Python have prompted me to evaluate an object's property or method to check if it even exists before proceeding, often resulting in the following pattern:
var value = collection.length
if value != null {
if value == targetValue {
/* do something */
}
}
In an attempt to make "cleaner" code I want to do something like:
if value != null && value == targetValue {
/* do something */
}
or with a ternary operator:
var value = collection.length != null ? collection.length : 0
However, I'm never sure if the compiler will stop evaluating as soon as it resolves the first comparison to null, or if it'll keep going and produce an error. I can of course do small unit tests to find out but I'd prefer if I knew the right term to look up in any language's documentation. What is this term, or is it perhaps the same in all languages?
This is known as Short Circuit Evaluation . It's quite consistent between languages.
In most languages, && will only evaluate the second argument if the first was true, and || will only evaluate its second if the first was false.

Proper term for 'if (object)' as a non-null test?

In ActionScript 3, you can check if a value exists like this:
if (object) {
trace("This object is not null, undefined, or empty!")
}
I frequently use this as a shorthand for if (object != null)
Is there a proper term for evaluating objects for null in this fashion? I suppose it's a matter of the Boolean typecasting rules for the language but I'm not sure if there's a name for the resulting syntax.
If your object is always an actual object reference, e.g. a variable of any object type, then checking if (object) is a valid way to test for nulls. If it's a property of variant type, or a dynamic property that can potentially contain simple values (ints, strings etc) then the proper way to test for null will be explicit conversion, probably even with a strict type check if (object !== null).
Like most computer languages, Ecma-script supports Boolean data types;
values which can be set to true or false. In addition, everything in
JavaScript has an inherent Boolean value, generally known as either
truthy or falsy
list of falsy values (non truthy)
false
0 (zero)
"" (empty string)
null
undefined
NaN (a special Number value meaning Not-a-Number!)
regularly for checking if a variable is null
you may use : (a == null) this statement returns true if a is null, But also return true for all of the above list, because they'r all falsy values and (a == undefined) returns true, even a is not undefined but null or 0 or false.
so you should use Identity operator in this case. following evaluations just returns true when a is null
(typeof a === "null")
// or
(a === null)

CoffeeScript idiom to either call function or property getter

An objects property can be a simple property or a function. Is there some easier way in CoffeeScript to get the value of this property?
value = if typeof obj.property is "function" then obj.property() else obj.property
I don't know if it is idiomatic but you could use (abuse?) the existential operator for this purpose.
When you say this:
obj.p?()
# ---^
CoffeeScript will convert that to:
typeof obj.p === "function" ? obj.p() : void 0
so if p is a function, it will be called, otherwise you get undefined. Then you can toss in another existential operator to fall back to obj.p if obj.p?() is undefined:
obj.p?() ? obj.p
There is a whole in this though, if you have:
obj =
u: -> undefined
then obj.u?() ? obj.u will give you the whole function back rather than the undefined that the function returns. If you have to face that possibility then I think you're stuck writing your own function:
prop = (x) ->
# Argument handling and preserving `#` is left as an exercise
if typeof x == 'function'
x()
else
x
and saying x = prop obj.maybe_function_maybe_not.
Demo: http://jsfiddle.net/ambiguous/hyv6pdtc/
If you happen to have Underscore around, you could use it's result function:
result _.result(object, property)
If the value of the named property is a function then invoke it with the object as context; otherwise, return it.

How can I query substring of nullable varchar with linq to sql?

I'm trying to import address data from some a database where there was not much data integrity. So there are a number of addresses (even in the US) that don't have postal codes and they're being read in as NULL.
I'm trying to do some matching of these addresses against an existing clean address database. I'm determining matches based on Addressee (company name), State (District), City (Locality) and either Street1 OR the first 5 of the postal code.
I tried this:
//This is just coded for the example -- In my routine, potentialAddress
//is coming from a data source where Postal Code may or may not be null.
Address potentialAddress = new Address() {
Street1 = "2324 Lakeview Drive",
PostalCode = null,
CountryId = 234, //US
Locality = "Sanford",
District = "FL"
};
//What I want here is Country & District have to match and either
//Street matches OR (if this is a US address) the first 5 of the postal code matches
_context.Addresses.Where(a => ((a.Street1 == potentialAddress.Street1)
|| (a.PostalCode != null && potentialAddress.PostalCode != null && potentialAddress.PostalCode.SubString(0,5) == a.PostalCode.SubString(0,5))
&& a.CountryId == potentialAddress.CountryId
&& a.District == potentialAddress.District).Select(a => a.Id).ToList();
I'm constantly getting an error message whenever potentialAddress is null. I'm getting:
Object reference not set to an instance of an object
when the query generator tries to parse potentialAddress.SubString(..).
I don't want to call it a match by postal code if one or the other (or both) are null.
Any ideas?
It seems as though the issue had to do with evaluating the potentialAddress object within the query. IOW, a.PostalCode != null was evaluated and a false value would stop any further processing of the condition whereas potentialAddress.PostalCode != null seemed to be ignored and the evaluation of the statement continued -- causing an error when it hit potentialAddress.PostalCode.SubString(0,5).
The only way I got around this was to move the conditional code dealing with potentialAddress outside of the query.
So, I now have something like this:
if(potentialAddress.PostalCode == null || potentialAddress.PostalCode.Length < 5)
//Perform query that ignores postal code
else
//Perform query that performs substring of postal code comparison
endif
Sure would've been nice if I could do that all in the query itself. Maybe someone could explain why the evaluation of potentialAddress.PostalCode in the query doesn't seem to work.

AS3: Null object reference when attempting to check if it exists?

I have a weird problem. An Object is being passed to my function, and some parameters are optional, so naturally I would check to see if they are there, and if not, do nothing.
However, I'm getting a null reference error (#1009) when I'm just checking it. Here's the sample:
public function parseObject(params:Object) {
if (params.optionalParam)
trace("Got Optional Parameter!");
}
The error is returned on the line with the if statement. Changing it to check for null (if (params.optionalParam == null)) doesn't work either. The players seems to just give up if an object doesn't exist.
Is there any logical reason for this to happen? Or is it some weird bug that has just surfaced?
Thanks in Advance,
-Esa
If your params object is null, then you will get a null reference error when trying to access its' optionalParam property.
Try something like:
if (params == null)
{ trace("params is null!"); }
else if (params.optionalParam != null)
{ trace("Got optional parameter!"); }