I am writing one small function which validates one text, and I am very upset because of the validation.
Problem is, why I try to compare the string to null (to check the cancel button), it works depending on where I put the condition! It seems to be working only when I put at the beginning of the validation. I have tested it with parenthesis for each condition too, but i get the same result.
Could someone explain me what´s happening here?
I found this answer on SO but it is for Python and I don´t understand it very well:
Does the Order of Conditions affect Performance?
text=prompt("Enter one text between 1 and 10 characters, no empty, blank spaces, only numbers");
WITH NULL (CANCEL BUTTON) VALIDATION AT THE BEGINNING,
if(text !=null && (text.length>=1&&text.length<=10) && text !="" && isNaN(text)==false)
WITH NULL (CANCEL BUTTON) VALIDATION AT ANOTHER POSITION,IT DOESN´T WORKS:
It generates "TypeError:Text is null"
if( (text.length>=1&&text.length<10) && isNaN(text)==false && text != "" && text !=null)
//some code when validation is ok
Because let's say that we had the following values:
var text = 'Tim is an alright person', notText = null
If we try to access a property of
notText, we will get an error because
null doesn't have a properties like
length. So, in code:
text has a
length property. However, the following does not work:
because notText does not have a length property. It will throw the error of TypeError because you are trying to do something with the
null type that is not allowed.
So, we need the
text != null check first because it will fail early, before trying the other expressions.