Useful NaN

    What is most known about NaN is that it is not equal to itself.

    NaN === NaN // false

    And that operations that are impossible arithmetically will return NaN.

    'BlaBlaBla'/0 // NaN

    But NaN has one little known (?), And, it seems to me, a very useful application.

    TL; DR It's all about Date


    In a nutshell:

     new Date(NaN) // Invalid Date 

    What is useful? Invalid Date is Date anyway. And all Date operations are still in place.
    Any Date operations other than setting the timestamp directly will return NaN, leaving Date as an Invalid Date.

     
    const x =  new Date(NaN) // Invalid Date 
    x.setTime(12345) // 12345
    x.toString() // "Thu Jan 01 1970 00:00:12 GMT+0000 (+00)"
    

    At the same time, checking for the validity of the date becomes easier nowhere

     
    const x = new Date(NaN) // Invalid Date 
    isNaN(x) // true
    x.setTime(0)
    isNaN(x) // false
    

    Note that conversion to timestamp is not required here, valueOf () does this under the hood.

    All operations with Date are mutable. However, cloning through the constructor works just fine with Invalid Date.

     
    const x =  new Date(NaN) // Invalid Date 
    const y = new Date(x) // Invalid Date
    

    Comparing two dates directly in Date is not implemented and you can only compare dates through timestamp. NaN guarantees that Invalid Date will definitely not be equal to any other date. I think this is a very useful property.

     
    const x =  new Date(NaN) // Invalid Date 
    const y = new Date(NaN) // Invalid Date
    x.getTime() === y.getTime() // false
    

    Unfortunately, the Date constructor behaves somewhat strangely with respect to the input parameter.

     new Date(null) // Thu Jan 01 1970 00:00:00 GMT+0000 (+00) 

    It would be much more logical to construct an Invalid Date, because null is not quite zero. Let's leave this to Javascript's conscience.

    However, if you forcefully pass undefined to the constructor, the result looks as expected. So be careful.

     new Date(undefined) // Invalid Date 

    The article turned out more about Date than about NaN, but, in general, I wanted to talk about this particular bunch.

    Also popular now: