Aside
One can accept that the author is self-documenting the code for the learner’s benefit. However, how clear a path it takes is debatable, IMHO.
Code design might more easily evolve from purpose, rather than identity, and the above is a good example to demonstrate this.
We have two arrays, let’s call them p
and q
that may or may not contain similar entries. Our task is to find any that exist. That’s the purpose of any function we write. I use small variables at this stage so they don’t clutter the canvas.
In loop constructs, it also makes little sense to me to use large variables when simple iterator variables are clearly understandable and do the job. Verbosity at this stage is overkill. A comment or two can take their place.
const p = ['Banff', 'Jasper', 'Lake Louise', 'Field', 'McBride'];
const q = ['Lake Louise', 'Waterton Lakes', 'Field', 'Fernie'];
We’ve settled upon a nested loop construct to compare and extract the matching data points (array elements) and can adopt the customary, i
and j
to fill the role of indexes.
for (let i = 0, j; i < p.length; i++) { // j is block scoped to i
for (j = 0; j < q.length; j++) {
console.log(p[i] === q[j] ? p[i] : '\t');
}
}
Rather than mess around in your workspace, let’s take this to Chrome’s JS console and input it.
> const p = ['Banff', 'Jasper', 'Lake Louise', 'Field', 'McBride'];
<- undefined
> const q = ['Lake Louise', 'Waterton Lakes', 'Field', 'Fernie'];
<- undefined
> for (let i = 0, j; i < p.length; i++) {
for (j = 0; j < q.length; j++) {
console.log(p[i] === q[j] ? p[i] : '\t');
}
}
8
Lake Louise
5
Field
5
<- undefined
The output matches our expectations. Now if we wish to create slightly more verbosity for the reader, a little replacement editing and we’re done. I find a simple approach best for testing and proving. You, too, will find your comfort zone, and a level of self-documentation that meets your team’s expected standards.
Simple is best. Better, in my view, to have simple variables and a comment table that describes them, than to have verbose self-describing variables that go over the top.
/* IDENTITY TABLE
let p == myPlaces
let q == friendPlaces
let i == myPlacesIndex
let j == friendPlacesIndex
*/
This is not to dis the instruction or the author’s approach. Far from it; but rather it is a way to see the flow of the current through a simpler lens. Granted, it is also a model to follow, in my view, but again that’s opinion.
The numbers printed in the output are the number of tab characters sent to the console. First eight, then a hit on ‘Lake Louise’, then five and another hit on ‘Field’, then five more and we’re exhausted.
Twenty object combinations, eighteen negatives and two hits.
Remember, this is modeling code, not solution, but it gives us the results we want, and then some.