Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does assignment in while condition check?

while(a = foo())
{
    bar();
}

Is this checking:

  • If assignment is successful, run bar, or
  • If a is defined and non-null, run bar, or
  • Something else ?
like image 920
Robert C. Holland Avatar asked Aug 22 '26 19:08

Robert C. Holland


1 Answers

On every iteration, it assigns the result of the foo() call to a, and if that result was truthy, it runs the loop and tries again until the result of the call is falsey.

For example, while assigning inside a condition is generally a code smell, it's seen often enough when trying to iterate over capture groups in a global regular expression:

const str = 'abcdefg';
const pattern = /(.)./g;
let match;
while (match = pattern.exec(str)) {
  console.log('first captured group was ' + match[1]);
}
// after the last iteration, `match` is null, so the loop stops

If the assignment is not successful, and the cause of that non-success would throw an error, then the whole script stops due to the error. (unless there's a try / catch block around it)

like image 109
CertainPerformance Avatar answered Aug 25 '26 10:08

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!