pyy
pyy

Reputation: 965

.filter() in javascript/typescript

  .filter(
    (item) => {
      console.log(this.timeFilter);  // line 1 
      if(this.timeFilter == NaN ) { return true; }   // line 2
      console.log("why log this?"); // line 3
      return item.endTime < this.timeFilter;
    }
  )

my code is above, I have a question that even if the this.timeFilter == NaN, it does not go the line 2, but go line 3 actually, not so sure what happened

NaN // line 1 output
why log this?  // line 3 output happen

Upvotes: 1

Views: 429

Answers (2)

mehulmpt
mehulmpt

Reputation: 16597

NaN == NaN returns false in javascript. This is to prevent operations like

'somename' / 5 == 'someothername' / 5; // should not return true (both are NaN)

Use isNaN:

if(this.timeFilter == NaN) should be actually if(!isNaN(this.timeFilter))

Upvotes: 3

MysterX
MysterX

Reputation: 2378

This is an incorrect comparison. You need to use function isNaN(). Something like next:

.filter(
    (item) => {
      console.log(this.timeFilter);  // line 1 
      if(isNaN(this.timeFilter)) { return true; }   // line 2
      console.log("why log this?"); // line 3
      return item.endTime < this.timeFilter;
    }
  )

Upvotes: 2

Related Questions