While having trust issues is not considered a positive thing in the “normal” world, if you work in the programming field, this is a necessity. Why? Most programs interact with end users in some shape or fashion. When we allow end users to play apart in our program, there is always a chance of something going wrong. Here are some possibilities…
- Asking the end user for a number and they put in text
- Needing certain pieces of information and the end user does not provide it
Plus many other scenarios. Fortunately, programming languages provide us with ways to protect our programs and provide a nice experience for end users.
There are many ways to ensure that the end user provides you with the necessary information for your program to run. For example, in HTML5, there is a required attribute. In JavaScript, you can also test to see if a field is empty with an ‘IF’ statement.
[code lang=”js”]
// Create empty variable
var emptyVar = "";
// Test to see if the variable is empty
if(emptyVar === ""){
// Do something
}
[/code]
Another example is working with integers and strings. We want to avoid concatenation errors. So that is where numeric functions come into play. We also have the ability to test whether data is a number or not. We can do that with the isNaN() method.
The isNaN() method is an interesting method because it may not be as intuitive as one thinks unless they break down what the function is asking. Right off the bat when looking at a number such as 123, one would want to know if that is truly an integer or not and expect to receive a true response. When run through the isNaN() funtion, the response is false. Let’s break down what the function is asking…isNaN()…basically, it is asking, “Is the information pass to me not a number?” In other words, as in our example, “Is ‘123’ not a number?” Well, ‘123’ is a number. So the answer is false. Another way of looking at this function is if you want integers, look for false responses. Otherwise, it is text.
[code lang=”js”]
// Create variables to house data to test
var testVar1 = isNaN(123);
var testVar2 = isNaN(-1.23);
var testVar3 = isNaN(5-2);
var testVar4 = isNaN(0);
var testVar5 = isNaN("Hello");
var testVar6 = isNaN("2014/15/09");
// The aforementioned would result in the following boolean output
false
false
false
false
true
true
[/code]
I know for some that isNaN() can be somewhat confusing. I hope the code examples clarifies things for you.
Happy Coding!
Clay Hess