⬆️ ⬇️

Useful NaN

About NaN is most known that he is not equal to himself.



NaN === NaN // false 


And that operations, impossible arithmetically, will be returned to NaN.



 'BlaBlaBla'/0 // NaN 


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



TL; DR It's All About the Date



In a nutshell:

')

  new Date(NaN) // Invalid Date 


What is useful? Invalid Date is still Date. And all operations with Date are still in place.

Any operations with Date other than directly setting the timestamp will return NaN, leaving the 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 is nowhere easier



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


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



All operations with Date are mutable. However, cloning through the designer works great 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 dates can only be compared via timestamp. NaN guarantees that the Invalid Date will definitely not be equal to any other date. I think this is a very useful feature.



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


To my regret, 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 design Invalid Date, because null is not quite zero. Let's leave it to Javascript conscience.



However, if forcibly transferred to the constructor undefined, the result looks 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 tell about this bundle.

Source: https://habr.com/ru/post/336124/



All Articles