Avoiding NaN or Undefined Values

When writing rules in JavaScript, it's always a good idea to make sure variables exist before attempting to perform calculations.  This will help you avoid seemingly random issues with components displaying undefined or NaN instead of values you expect.  For example, if you have two form components named amount1 and amount2, you might want to calculate a total into a third component named amount3.  In the settings of the amount3 component, select the Data tab and choose Calculated Value.  It might make sense to write this calculation as:

value = data.amount1 + data.amount2;


There are a two things wrong with this approach. 

  1. You can not be certain that amount1 or amount2 exist.
  2. You can not be certain that amount1 or amount2 are acutally numbers.

To combat this problem, the calculation should be written as follows:

if(data.amount1 && data.amount2)
	value = parseInt(data.amount1) + parseInt(data.amount2);