openlang

The array nobody asked for

CoffeeScript returns the last expression of every function, and a for loop is an expression. So a handler that ends in a loop written for its side effects compiles to JavaScript that collects every iteration's value into an array and returns it. Nobody reads that array. The docs suggested ending such functions with true or null, and I still catch myself typing a trailing null in plain JavaScript, where it does nothing.

后续讨论 4

顺着彼此的依据读下去
  1. 固定链接

    ReScript returns the last expression too and never builds that array, because a for loop there has type unit. An unused value mid-block gets a warning suggesting ignore, and I'm not sure what that teaches a learner.

  2. 固定链接

    The array is the harmless case. The interesting one is a handler whose last line happens to be a boolean.

    If the handler is attached with addEventListener, the return value is ignored and whatever the loop or comparison produced is just garbage. If it's assigned to onclick, a returned false cancels the default action. If it's a jQuery handler, false also stops propagation, because jQuery treats it as preventDefault() plus stopPropagation(). So the same compiled return is noise in one setup, a link that won't follow in another, and a click the parent never hears about in the third.

    A refactor preview that marks the implicit return as unused would be wrong in two of those three. It should say where the function is attached before it calls anything dead.

  3. 固定链接

    That one did more damage than the arrays ever did (and I suspect it's a good part of the reason the advice existed at all, since a trailing null or true keeps jQuery quiet where a stray false does not, and the docs never quite spelled that out). The usual victim was a toggle. A click handler ending in @open = not @open compiles to return this.open = !this.open;, which returns false on every second click. Every other click toggled the panel and also ate the event. It looks like a flaky toggle until you read the compiled return line, which is an easy line to read past.

  4. 固定链接

    Plain JavaScript still has the concise arrow. useEffect(() => fetchList()) hands React a promise and the dev console complains, and useEffect(() => { fetchList() }) returns undefined, which is roughly what that trailing null was for.

同一个问题的其他角度

  1. Notation first, machine later

    APL was a notation before it was a program. Iverson used it on paper to describe algorithms, and the 1962 book A Programming…

    回复 1最近活动 apl
  2. Where Pharo code actually lives

    Poking at Pharo after a long time with Ruby, and I'm stuck on something embarrassingly basic for someone used to files. I mad…

    回复 1最近活动 smalltalk
  3. A useful review comment on a retain cycle names the owner

    “Just use weak everywhere” is a review comment the author can't really answer. The usual case is a child object holding a del…

    回复 1最近活动 swift