0

I have this bit of code inside a function. It is supposed to filter a global variable RESTRICTIONS to any keys that start with this.label. In this example RESTRICTIONS=={"lm.tags": "something"} and this.label=="lm". It has the opposite result from what is expected! I actually want it to match, which it does. But I would expect to use > and not == inside the filter function. Even if pause the code on this line and run other tests using literal strings or any variable set to "lm" it works the way you would expect, but when I set search lm.label it starts working backwards! It makes no sense!!! Is it some kind of bug? I am using Chrome 80 on Windows.

var matchingKeys = Object.keys(RESTRICTIONS)
                         .filter(function(x){
                            return x.indexOf(this.label)==-1
                         })

//result: ["lm.tags"]
//expected: []
Moss
  • 3,695
  • 6
  • 40
  • 60
  • I can even say `myvar = this.label` and then run this line with myvar and it works normally!?!?!?! – Moss Apr 13 '20 at 21:35
  • 3
    `this` inside the filter function is different from wherever else you have it – Anurag Srivastava Apr 13 '20 at 21:37
  • @AnuragSrivastava what do you mean? – Moss Apr 13 '20 at 21:39
  • 1
    If you `console.log(this.label)` inside your filter function, you will get `undefined`, and the return condition is always true so you get the result as you are now – Anurag Srivastava Apr 13 '20 at 21:42
  • @ChrisG Oh, duh, this is changing inside the filter function. Now I understand what Anurag meant. Figures it was something dumb like that. I guess I was assuming this works like normal variable scope. – Moss Apr 13 '20 at 21:42
  • You might get expected results with arrow functions – Anurag Srivastava Apr 13 '20 at 21:43
  • Should I delete this question or change the title now that I know the real problem? – Moss Apr 13 '20 at 21:43
  • 1
    @AnuragSrivastava, you are right! arrow function is different! Smart, but unintuitive. – Moss Apr 13 '20 at 21:45
  • I have a sneaky suspicion I ran into this problem years ago, and posted on Stackoverflow. Haven't been coding for awhile. – Moss Apr 13 '20 at 21:46

0 Answers0