0

I have a user database like this:

const user = {
  subscription: {
    plan: 'free_trial',
  },
};

I need to check some condition before user changes plan.

const currentDate = new Date();
if (user.subscription.trialExpDate > currentDate) {
  // do something
} else {
  // trialExpDate is either undefined or <= currentDate
  user.subscription.trialExpDate = currentDate;
}

My question is, for some users trialExpDate will be undefined. Is it okay to compare undefined against currentDate object? Or do I need to check if trialExpDate exist first?

cocacrave
  • 2,453
  • 4
  • 18
  • 30

3 Answers3

3

I would suggest check with hasownproperty. Sample:

if (user.subscription.hasOwnProperty('trialExpDate') && user.subscription.trialExpDate > currentDate) {
  // do something
} else {
  // trialExpDate is either undefined or <= currentDate
  user.subscription.trialExpDate = currentDate;
}
kernal_lora
  • 1,115
  • 3
  • 12
  • 25
  • Thanks I'll do that instead :) – cocacrave Oct 02 '16 at 03:39
  • 1
    `trialExpDate` is not `ownProperty` of `user` object, it belongs to `user.subscription` – Rayon Oct 02 '16 at 03:40
  • 1
    What if `user.subscription.trialExpDate` is `null` ? It will return `hasOwnProperty` `true`.. I will go with `if(user.subscription.trialExpDate && .....)` – Rayon Oct 02 '16 at 03:42
  • 1
    Yes, @Rayon that is one scenario. If we are confident that won't be null we can use hasownproperty otherwise your we have to check as you said – kernal_lora Oct 02 '16 at 03:46
1

You can just check if it is null.

if (user.subscription.trialExpDate != null || user.subscription.trialExpDate > currentDate) {
    // do something
}
else {
    // do something else
}

The variable != null will simultaneously check if the variable is null or undefined.

Rax Weber
  • 3,730
  • 19
  • 30
0

In short: if you're sure that user.subscription.trialExpDate cannot be a null, using your original code is very okay.

See how the JavaScript relational comparison operators coerce types.

If user.subscription always exist and it is always an object, comparison between a Date object, and an undefined or a NaN, is evaluated as false. However, for a null, it is evaluated as +0, thus null < (new Date) will be true, null > (new Date) will be false.

When JavaScript relational comparison works,

  1. A Date object is converted to its timestamp, which is (The Date object).valueOf().

  2. A primitive is converted to a number, which means:

    • an undefined is converted to a NaN;
    • a null is converted to +0.
  3. Then the comparison is performed between each item as you'd expect for the operator. Note that any comparison involving a NaN evaluates to false.

Community
  • 1
  • 1