Seek and Destroy: Variable Scope warning

Seek and Destroy: Variable Scope warning
0

#1

Hello
I am getting the following alert ‘functions declared within loops referencing an outer scoped variable may lead to confusing semantics’ on line 7 . I think I get it that the args array is defined outside the for loop (hence outside function(x)'s scope. But how would I go about to reference args[i] in the for loop to make the comparison?

Your code so far

function destroyer(arr) {
  // Remove all the values
  var newArr = arguments[0];
  var args = arr.prototype.slice.call(arguments, 1);
  for (i=1;i<args.length; i++){
    newArr = newArr.filter(function(x){
      return x != args[i];
  });
}
  
}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

Your browser information:

Your Browser User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.12; rv:56.0) Gecko/20100101 Firefox/56.0.

Link to the challenge:


#2

The warning is thrown since you are trying to assign a new value to newArr, which is declared outside of the loop scope.

This is indeed a bad practice, and may cause bug in your code.
What you have created there is a perfect example of one: a new value will be assigned to newArr at each iteration of the loop.

In this case newArr will be:

[1,3,1,3] //first iteration
[1,1] // second iteration

Which may be a desired effect, but it’s not as immediate by looking at your code, hence the warning.

That said, those are warnings thrown to help you writing code in a more meaningful way, but won’t prevent your code to run.

To solve this issue you could simply remove the for loop entirely: you don’t need it: filter is already a function that iterates over each element of the array, so why the need of loop?

hint: there are other methods to see if an element is present in an array besides x != args[i]


With that in mind your code still has a couple of issue:

1: mind how you access Array.prototype

var args = arr.prototype.slice.call(arguments, 1); // cannot read property slice of undefined

2: where exactly is i defined? Why start looping from 1?

for (i=1;i<args.length; i++)

Hope it helps :+1:


#3

Thanks a lot. this was very helpful.