CRec CRec - 5 months ago 27
jQuery Question

using ! operator or $.IsNumeric in javascript?

I have a condition that needs to be validated with a string on one side and a decimal in the other side. However if the second condition is null this should return true, to enter and display my is required message.

if (!equipObject[i].Mass[0].massId && !equipObject[i].Mass[0].Price ) {
// display message - either massId or Price are required!

however I am thinking about changing the second condition




How are these two validations different? which one is optimal? 0 is not a valid price according to the BL.



They're very different and do essentially totally different things


Here you take a "value" and it's coerced into a true/false value and then a "not" is applied. So if we replace equipObject[i].Mass[0].Price with actual values you get the following results:

!0 //true
!1 //false
!2 //false
!0.00 //true
!1.8884441 //false
!"1.8884441" //false
!"one" //false
!true //false
!false //true
!null //true

Etc. So this isn't very type safe.


this utilises jQuery's isNumeric function.

The $.isNumeric() method checks whether its argument represents a numeric value. If so, it returns true. Otherwise it returns false. The argument can be of any type.

So let's do the same:

!$.isNumeric(0) //false
!$.isNumeric(1) //false
!$.isNumeric(2) //false
!$.isNumeric(0.00) //false
!$.isNumeric(1.8884441) //false
!$.isNumeric("1.8884441") //false
!$.isNumeric("one") //true
!$.isNumeric(true) //true
!$.isNumeric(false) //true
!$.isNumeric(null) //true

so very different results.

which one is optimal?

That depends on your definition of optimal. I'm presuming you actually want to check if something is an integer and greater than zero, in which case I think you need a third way:

!$.isNumeric(equipObject[i].Mass[0].Price) && equipObject[i].Mass[0].Price !== 0

notice the !==. This prevents coercion