If you want to make a complex single-line loop style, the โcorrectโ syntax is:
var array = ['a', 'b', 'c']; for (var i = 0, rowName; rowName = array[ i++ ]; ) { console.log(rowName); }
Pay attention to the ending ; t22 cycle declarations. There is a technically empty statement after ; where you usually do i++ .
In this case, the "condition" of the for loop uses the Javascript assignment operator. If you have a code like this:
var a; if( a = 1 ) { // Note this is assignment = not comparison == console.log('true'); }
He will keep a log of "true". What for? Since inside the expression a = 1 really returns 1 . And 1 is โtrueโ, which means that it evaluates true in a logical context such as an if .
The opposite is also true if your meaning is false:
var a; if( a = 0 ) { console.log('true'); }
It will not register, because a = 0 returns 0 (and also assigns 0 to a ). And 0 is false.
This brutal for-loop syntax is for specific conditions only:
- If any of the elements of the array is "falsey" (
null , undefined , "" , etc.), it will terminate the loop prematurely due to the way the operators work, as described above. - This suggests that you do not need the loop index
i . It will be disabled by 1 for each iteration of the loop, because i++ runs before the for block. That is, the first time the for body is executed, i will be 1, not the declared initial value 0. - The only advantage of this pattern is the storage of several bytes. It is not used at all in the real world because of the above two pitfalls.
source share