So I think this would be a useful time to walk through your code step by step and think about what each line is doing.
On the first line, you’re declaring a function called diffArray
that takes two parameters - which at runtime will be assigned the variable names arr1
and arr2
respectively within the function scope.
Then, inside the function, you declare a variable called newArr
that gets the value of an empty array.
Next, you declare a for
loop. In the for loop’s scope, you declare a variable called i
and set it equal to zero, and you tell the for loop to check the value of i
against the aforementioned arr1
's length property each “pass through the loop” as it were. Finally, the for loop, increments the value of i
after each pass through the loop. The order in which these occur is important and occurs in a somewhat less than intuitive manner if you’re new to looping - you should read here about the for
statement just to make sure you understand the order in which things are occurring in the loop.
The logic inside the for
loop is the next line (at the if
statement). In the if
statement, you tell the interpreter to check the value of arr2.indexOf(arr1[i] === -1))
. This is where I think you should really evaluate what you’re doing. In the arr2.indexOf()
method, you’re passing an expression that will evaluate to a Boolean. So effectively, you’re going to get either arr2.indexOf(true)
or arr2.indexOf(false)
, no matter what. You won’t be able to find an index of the value(s) true
or false
in the arrays being passed to your function. Additionally, if a matching value is not found, indexOf
's return value is -1
. It looks like you read the docs here, but your implementation is a little bit off
Finally, IF the if
statement’s expression evaluates to a truthy value, you say: push to my variable newArr
(which is an array, so push is appropriate here) the value arr1[i]
--> (so if i = 1
, you’d be pushing arr1[1] which evaluates to to 2
, and so on…).
You might rewrite the code you have above as I’ve done here
That is a REALLY great tool for solving these sorts of problems, by the way. Play around with it, it let’s you step through every iteration of a loop and shows you all the values of all variables in scope. It really helped me nail down loops when I was first learning them.