Loading ...
Sorry, an error occurred while loading the content.

3137Re: [jslint] init of for

Expand Messages
  • John Hawkinson
    Feb 25, 2013
    • 0 Attachment
      Heinz Rasched <raschedh@...> wrote on Mon, 25 Feb 2013
      at 12:37:13 -0000 in <kgfltp+agd7@...>:

      > function f(an_array) {
      > 'use strict'
      > var i = 0,
      > n = an_array.length;
      > for (; i < n; i += 1) {
      > // operate on an_array[i]
      > }
      > }

      From an idempotency perspective, you're better off with the
      the initialization in the for loop anyhow. Because it's common
      for functinos to be long enough that review of all the code
      between initialization and loop may be burdensome, as is reuse
      of loop variables in multiple loops. If you therefore had:

      var i=0;
      for (; i<n; i +=1 ) { /* some loop */ }
      for (; i<n; i +=1 ) { /* some other loop*/ }

      then i would be zero for the first for() but not the second.

      It's nice for the for loop to be self contained. One can look
      at the loop itself and immediately understand it, without having
      to worry about initialization that might be far away from it.

      JavaScript's lack of block scope really suggests that the variables
      you should initialize at the top of a function are those whose value
      is expected to stay constant throughout the function.

      This sort of generalization matters more for longer functions, of

      John Hawkinson
    • Show all 8 messages in this topic