Live data from Hacker News

Code Conventions for the JavaScript Programming Language

javascript.crockford.com

11–20 of 31 posts

Re: Code Conventions for the JavaScript Programming Language

#11
post #4

Some are good, some arbitrary: Is the 80 col limit still valid in the modern day with such large screen displays? . His line indentation convention is inconsistent. In one place he says to use 8 spaces, in another he says to use 4. Then when you look at a switch, its 0. . variable declarations: If he's referring to the way that JSLint enforces it, that's stupid. ex: function foo(){ myGlobal = "foo"; } var myGlobal; "…

Few of the examples you listed are arbitrary, in fact Crockford describes precisely why he chose them as conventions. In nearly all cases he came up with these conventions to help coders avoid common pitfalls due to unfortunate aspects of the JavaScript language.

    function foo(){
       myGlobal = "foo";
    }

    var myGlobal;
This is clear if you only have this one function, but with a large js file I know I'd rather not be searching through the code for global variables. That's also why "Inner functions should follow the var statement", it's an easy way to keep track of scope.

"Do not use _ (underbar) as the first character of a name. It is sometimes used to indicate privacy, but it does not actually provide privacy. " It's private because you weren't invited to use it, not because I have a bomb waiting for you.

No, it's private because it throws an error if you try to use it outside of the proper scope. From what I can tell about Python, for example, adding underbars enforces privacy, JavaScript doesn't.

"Global variables should be in all caps." umm, no. That convention is reserved for constants.

That convention in other languages is for constants. Crockford points out that js doesn't have constants. He also constantly points out the dangers of global variables, how you should minimize their use. The purpose of all caps is to give a visual cue that they're global, the purpose of all caps in other languages is to give a visual cue that they're constants.

"Each group of statements (except the default) should end with break, return, or throw. Do not fall through." Arbitrary. I think DRY is preferable when it's warranted.

Crockford used to think the same. He tells the story of a user who suggested fall-through should be flagged by JSLint. Crockford gave him a detailed response explaining that there was nothing wrong with fall-through. The user agreed, and included a bug report for JSLint in his response. Crockford found the bug in JSLint and it was caused by... fall-through.

"Avoid doing assignments in the condition part of if and while statements. " It's a legitimate convention if wrapped with an extra pair of parenthesis. Note that Mozilla's strict mode will honor this convention.

Crockford points out the problems you can run into doing that:

Is

    if (a = b) {
a correct statement? Or was

    if (a == b) {
intended?

It's easy enough to tell if you're the one who wrote it, but what happens to the poor sorry schlub who's trying to debug the code later on (especially if that schlub is you 6 months later)?

Re: Code Conventions for the JavaScript Programming Language

#12

There are arguments for and against tabs and spaces. Crockford mentions one of these arguments and concludes that everyone should use spaces. Similarly for other "conventions". I would rather replace the whole article with "Write readable code". Following these conventions are neither sufficient or necessary to accomplish that.

1. The people for whom "Write readable code" is sufficient guidance are the same people for whom that guidance isn't needed in the first place.

2. For a body of code written by multiple people to be readable, it helps considerably if the conventions those people follow are consistent. A document like this one can help with that.

3. It doesn't seem reasonable to expect that the author of a document like this should provide all the counter-arguments to every position he takes. It's not an in-depth analysis of what constitutes good JavaScript code, it's just a set of coding conventions.

Re: Code Conventions for the JavaScript Programming Language

#13
post #9
post #4

Some are good, some arbitrary: Is the 80 col limit still valid in the modern day with such large screen displays? . His line indentation convention is inconsistent. In one place he says to use 8 spaces, in another he says to use 4. Then when you look at a switch, its 0. . variable declarations: If he's referring to the way that JSLint enforces it, that's stupid. ex: function foo(){ myGlobal = "foo"; } var myGlobal; "…

About the 80 lines width: yes, and it is much more important now than never (in my opinion). Have a look at most news websites, or at a normal book, or a newspaper, or LaTeX (and even Word!) standard text-width, it's all fitting in around that size because it is very efficient to read. Unlimited width for text is a UI anti-pattern, as the eye gets more and more pain to find the next line. A great example of site resp…

Typographers have known this for quite some time. It's called "measure" and it should be around 65-75 characters (according to the typographer's bible, The Elements of Typographical Style by Binghurst: http://en.wikipedia.org/wiki/The_Elements_of_Typographic_Sty...)

Re: Code Conventions for the JavaScript Programming Language

#14
post #5
post #3

"Avoid lines longer than 80 characters." This one really bugs me. 80 characters doesn't fit a whole lot of stuff. In a case where a line is more than 80 chars long I would rather see this: document.getElementsByClassName("externalLinkBig")[0].setAttribute("class", "externalLinkSmall"); than this rather ugly solution: document.getElementsByClassName("externalLinkBig")[0].setAttribute("class", "externalLinkSmall");

Personally, I find both examples from your post rather unreadable. I always chain method calls like this: document .getElementsByClassName("externalLinkBig")[0] .setAttribute("class", "externalLinkSmall");

That's ugly (IMHO) and not a good idea in js where semicolons are optional...

For all we know it may execute 'document' as a statement, and then the next lines.

Not nice IMHO

If you can fit 160 chars on the display, use 160.

Re: Code Conventions for the JavaScript Programming Language

#15
post #12

There are arguments for and against tabs and spaces. Crockford mentions one of these arguments and concludes that everyone should use spaces. Similarly for other "conventions". I would rather replace the whole article with "Write readable code". Following these conventions are neither sufficient or necessary to accomplish that.

1. The people for whom "Write readable code" is sufficient guidance are the same people for whom that guidance isn't needed in the first place. 2. For a body of code written by multiple people to be readable, it helps considerably if the conventions those people follow are consistent. A document like this one can help with that. 3. It doesn't seem reasonable to expect that the author of a document like this should pr…

For a body of code written by multiple people to be readable, it helps considerably if the conventions those people follow are consistent.

I'm not convinced of this (at least it doesn't hold true for me). I used to believe it, mostly because it seems to be common wisdom. But I've realized over time that I can just as easily read code that's written using K&R style braces, or BSD style, or even Whitesmiths, and it really doesn't matter to me whether indentation is 2, 4, or 8 spaces.

I think some of my point of view comes from being a heavy Emacs user and having written a lot of Lisp code in the past. I don't tend to see braces/parens much for example - I let the editor take care of them.

Re: Code Conventions for the JavaScript Programming Language

#16
post #4

Some are good, some arbitrary: Is the 80 col limit still valid in the modern day with such large screen displays? . His line indentation convention is inconsistent. In one place he says to use 8 spaces, in another he says to use 4. Then when you look at a switch, its 0. . variable declarations: If he's referring to the way that JSLint enforces it, that's stupid. ex: function foo(){ myGlobal = "foo"; } var myGlobal; "…

> Is the 80 col limit still valid in the modern day with such large screen displays?

Yes. With my previous notebook screen (1440x900) I could fit two 83-character-wide Emacs buffers side by side. With my current screen (1600x900) I can fit two 94-character-wide Emacs buffers side by side.

Re: Code Conventions for the JavaScript Programming Language

#17
post #4

Some are good, some arbitrary: Is the 80 col limit still valid in the modern day with such large screen displays? . His line indentation convention is inconsistent. In one place he says to use 8 spaces, in another he says to use 4. Then when you look at a switch, its 0. . variable declarations: If he's referring to the way that JSLint enforces it, that's stupid. ex: function foo(){ myGlobal = "foo"; } var myGlobal; "…

Few of the examples you listed are arbitrary, in fact Crockford describes precisely why he chose them as conventions. In nearly all cases he came up with these conventions to help coders avoid common pitfalls due to unfortunate aspects of the JavaScript language. function foo(){ myGlobal = "foo"; } var myGlobal; This is clear if you only have this one function, but with a large js file I know I'd rather not be search…

From what I can tell about Python, for example, adding underbars enforces privacy, JavaScript doesn't.

That's not true, an initial underscore is simply used as the convention to indicate that something is private:

    >>> class Foo(object):
    ...   def __init__(self):
    ...    self._bar = 48
    ...
    >>> a=Foo()
    >>> a._bar
    48

Re: Code Conventions for the JavaScript Programming Language

#18
post #4

Some are good, some arbitrary: Is the 80 col limit still valid in the modern day with such large screen displays? . His line indentation convention is inconsistent. In one place he says to use 8 spaces, in another he says to use 4. Then when you look at a switch, its 0. . variable declarations: If he's referring to the way that JSLint enforces it, that's stupid. ex: function foo(){ myGlobal = "foo"; } var myGlobal; "…

Few of the examples you listed are arbitrary, in fact Crockford describes precisely why he chose them as conventions. In nearly all cases he came up with these conventions to help coders avoid common pitfalls due to unfortunate aspects of the JavaScript language. function foo(){ myGlobal = "foo"; } var myGlobal; This is clear if you only have this one function, but with a large js file I know I'd rather not be search…

"This is clear if you only have this one function, but with a large js file I know I'd rather not be searching through the code for global variables. That's also why "Inner functions should follow the var statement", it's an easy way to keep track of scope."

And what about functions in the outer scope? Why should one be forced to place them in a particular order to use them in an inner scope? God forbid if you have this:

    function first(){
        //stuff
        someVal = second()
        //stuff
    }
    function second(){
        //stuff
        anotherVal = first()
        //stuff
    }
"No, it's private because it throws an error if you try to use it outside of the proper scope."

This is what I'm talking about:

    function Point(x, y){
        this._x = parseInt(x,10);
        this._y = parseInt(y,10);
    }
    Point.prototype = {
        get x() this._x,
        set x(v) this._x = parseInt(v,10),
        get y() this._y,
        set y(v) this._y = parseInt(v,10)
    }
You simply don't document the "private" properties. Pretending JavaScript is more robust than it is helps no one and wastes memory.

"That convention in other languages is for constants. Crockford points out that js doesn't have constants."

It's been supported since JavaScript 1.5.

"The purpose of all caps is to give a visual cue that they're global"

Hungarian notation works fine thank you.

"Crockford used to think the same. He tells the story of a user who suggested fall-through should be flagged by JSLint. Crockford gave him a detailed response explaining that there was nothing wrong with fall-through. The user agreed, and included a bug report for JSLint in his response. Crockford found the bug in JSLint and it was caused by... fall-through."

I don't see the relevance.

"if (a = b) {"

I've already pointed out that there is already a common, testable convention in place:

    if((a = b)){
Use Mozilla's strict mode and you'll be able to see the difference.

Re: Code Conventions for the JavaScript Programming Language

#19
post #12

Earlier quoted context omitted.

1. The people for whom "Write readable code" is sufficient guidance are the same people for whom that guidance isn't needed in the first place. 2. For a body of code written by multiple people to be readable, it helps considerably if the conventions those people follow are consistent. A document like this one can help with that. 3. It doesn't seem reasonable to expect that the author of a document like this should pr…

For a body of code written by multiple people to be readable, it helps considerably if the conventions those people follow are consistent. I'm not convinced of this (at least it doesn't hold true for me). I used to believe it, mostly because it seems to be common wisdom. But I've realized over time that I can just as easily read code that's written using K&R style braces, or BSD style, or even Whitesmiths, and it rea…

In terms of reading a complete body of code in one style or another, I agree.

What is annoying and distracting is having conflicting styles in the same single chunk of code. Sort of like how I would not want a book to randomly change line spacing, character spacing, etc. from paragraph to paragraph. I don't really care what the spacings are, and I certainly have no problem going from one book to another where these are totally different, but I do not want them flip-flopping around in the text of a single book.

Re: Code Conventions for the JavaScript Programming Language

#20
post #17

Earlier quoted context omitted.

Few of the examples you listed are arbitrary, in fact Crockford describes precisely why he chose them as conventions. In nearly all cases he came up with these conventions to help coders avoid common pitfalls due to unfortunate aspects of the JavaScript language. function foo(){ myGlobal = "foo"; } var myGlobal; This is clear if you only have this one function, but with a large js file I know I'd rather not be search…

From what I can tell about Python, for example, adding underbars enforces privacy, JavaScript doesn't. That's not true, an initial underscore is simply used as the convention to indicate that something is private: >>> class Foo(object): ... def __init__(self): ... self._bar = 48 ... >>> a=Foo() >>> a._bar 48

Au contraire, double underscore does make it "private". Trying to access a double underscore attribute directly will throw an AttributeError.

    >>> class Foo(object):
    ...     def __init__(self):
    ...             self.__a = 42
    ...     def look_here(self):
    ...             print self.__a
    ...
    >>> f = Foo()
    >>> f.__a
    Traceback (most recent call last):
      File "", line 1, in ?
    AttributeError: 'Foo' object has no attribute '__a'
    >>> f.look_here()
    42
Post reply on HN