Undefined value



One more best practice around the dot-walking concept. As we have already seen, dot-walking is a very easy and handy feature to use and as a result it is tempting to use it to dot walk several tables to get a required value. If any record is missing in such a long dot walked chain however, a dreadful javascript error would be thrown - "The Undefined value has no properties." As scary as that error sounds, a simple check that the value exists before using it or dot walking further would help your gr to be creative and show off a few Parkour moves.

Imagine you are working with an incident record and want to send an email to assignment group's manager's manager (This is an example, don't send emails to manager's manager. It generally doesn't go down that well). 

A normal code to access the value would look like below

return grInc.assignment_group.manager.manager.toString();

It could very well happen that the assignment group doesn't have a manager defined. Above line of code will fail in that case. One solution would be to check the value exists before using it. Updated check would look like below

if(grInc.assignment_group 
   && grInc.assignment_group.manager 
   && grInc.assignment_group.manager.manager) {
return grInc.assignment_group.manager.manager.toString();
}
//some of the dot walked values don't exist
return false;

It would ensure that the code doesn't fail due to a missing value in the dot walked chain. Now since this is in Javascript domain, be mindful of the field type you are accessing as well. A condition to check if the value exists using above syntax would return false in case the field has a falsy value. Examples would be 0 or an empty string.

I believe, optional chaining from ES2020 would be a better way to handle such checks. We can play with it as early as in the Tokyo release.









Creative Commons License

Comments