Home > Software design >  Differences between dayjs() of two strings
Differences between dayjs() of two strings

Time:12-11

I do not know why the following test output is false:

const test = "2022-12-10T06:51:00Z"

    if (dayjs(test) == dayjs("2022-12-10T06:51:00Z")){
        console.log('true')
    } else {
        console.log('false')
    }

although this test is true

const test = "2022-12-10T06:51:00Z"

    if (test == "2022-12-10T06:51:00Z"){
        console.log('true')
    } else {
        console.log('false')
    }

Could anyone please explain why the first test is false?

Thank you

CodePudding user response:

Because every time you call dayjs, it returns a new object. No matter the values that you are passing through is the same or not.

const obj1 = dayjs("2022-12-10T06:51:00Z");  
const obj2 = dayjs("2022-12-10T06:51:00Z");
console.log(obj1 === obj2);

As you can see obj1 and obj2 are two different objects with different references in memory. So they are not equal.

But when you compare two strings, if the values are the same, the comparison check becomes true.

const test = "2022-12-10T06:51:00Z";
console.log(test == "2022-12-10T06:51:00Z");

You can read more about object references and copying here.

  • Related