FranP FranP - 20 days ago 5
Javascript Question

why this javascript validation works depending on the order of conditions?

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?

Thanks

function validate()
{
var isValid=false;

var text;

while(isValid==false)
{
text=prompt("Enter one text between 1 and 10 characters, no empty, blank spaces, only numbers");




/*

WITH NULL (CANCEL BUTTON) VALIDATION AT THE BEGINNING,
IT WORKS:

*/

if(text !=null && (text.length>=1&&text.length<=10) && text !="" && isNaN(text)==false)
{
isValid=true;
}


/*

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)
{

isValid=true;




}




}

if(isValid==true)
{
//some code when validation is ok
}



}

Answer

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:

if(text.length){...}

works because text has a length property. However, the following does not work:

if(notText.length){...}

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.

Comments