Is the condition in the for loop computed in each loop?

I have a situation like:

for(var i = 0; i < a + b; ++i)
  // code that doesn't affect a and b

Do I have to worry about the addition being done at each iteration? Or is JavaScript (its parser?) Smart enough to understand what a + bis a constant?

In other words, should I do this as follows:

var end = a + b;
for(var i = 0; i < end; ++i)
  // code

or will this lead to the cancellation of a line of code?


Well, actually what I'm worried about is not just one line of code, but the fact that I think about it every time I come across a similar situation in JavaScript! In addition, today it is an addition, tomorrow it may be something else, like the square root of it, so I consider it important!

+4
3

:

for(var i = 0, end = a + b; i < end; ++i)

:

for(var i = a + b; i--;)

, i ,


. :

for(var i = 0; i < array.length; ++i) { 
   array.push('value'); // infinite loop
}

array.length , array.push().

+2

.

: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for

for ([initialization]; [condition]; [final-expression])
   statement

: , . true, . . , true. false, , .

( )

, : , , , .

, , Chrome Firefox.

: . :

" , , 97% : - . 3%"

, ( 1974). " ". ACM Journal Computing Surveys 6 (4): 268. CiteSeerX: 10.1.1.103.6084.

, . , , , .

TL; DR

, , , , javascript-, , .

, . ?

+3

, , a + b, , , . a b , .

0

Source: https://habr.com/ru/post/1609309/


All Articles