Another paren-free gotcha

Douglas Crockford douglas at crockford.com
Wed Sep 28 15:38:42 PDT 2011


On 11:59 AM, Waldemar Horwat wrote:
> Thinking about the implications of paren-free, I see additional 
> potential trouble spots in addition to the one I mentioned in the 
> meeting yesterday:
>
>> Start with ES5 code:
>>
>> if (a + b)
>>   (x.y)()
>> z++
>>
>> Now (erroneously) convert it to paren-free:
>>
>> if a + b
>>   (x.y)()
>> z++
>>
>> This doesn't give a syntax error; it silently changes the meaning of 
>> the program.
>
> Another hidden pitfall of the paren-free experience is illustrated by 
> the expression refactoring to add parentheses:
>
> Start with ES5 code:
>
> if (a + b/g > f) f = a + b/g
>
> Convert it to paren-free:
>
> if a + b/g > f {f = a + b/g}
>
> So far so good; it works.  However, later someone discovers that the 
> code had a logic error, the fix to which is to divide the sum a+b by c 
> instead of dividing only b by c.  So he fixes the code to:
>
> if (a + b)/g > f {f = (a + b)/g}
>
> Oops.  Now the / starts a regexp.  There is an extra closing brace 
> which will simply close the enclosing scope early, so a syntax error 
> likely won't appear for a while.

These are indeed concerns. But paren-free is still worthwhile. My view 
is in that in a statement like

     if (a + b/g > f) {f = a + b/g;}

that either the parens around the condition are optional, or the braces 
around the consequence are optional, but not both (with allowance for 
'if else'). My argument with Thompson and Ritchie is that they chose 
which pair was required, and they picked the wrong pair.


More information about the es-discuss mailing list