'Iterate over RegExp.exec(...)

From the RegExp.exec page on MDN, it gives the following example of iterating through a match with the g flag set:

const regex1 = RegExp('foo*', 'g');
const str1 = 'table football, foosball';
let array1;

while ((array1 = regex1.exec(str1)) !== null) {
  console.log(`Found ${array1[0]}. Next starts at ${regex1.lastIndex}.`);
  // expected output: "Found foo. Next starts at 9."
  // expected output: "Found foo. Next starts at 19."
}

I have two questions about this code. The first one is why the !=== null is used here, why wouldn't the while loop be properly coded as:

while (array1 = regex1.exec(str1)) { // implicitly casts to boolean?
  console.log(`...`);

}

The above seems much more readable to me, but was wondering why the MDN docs used the first approach? Second, is it possible to declare and define the variable directly in the while loop? Something like:

while (let array1 = regex1.exec(str1)) { // don't need the `let array1` above?
  console.log(`...`);

}

Or is that not supported in the JS language?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source