Live data from Hacker News

Code Conventions for the JavaScript Programming Language

javascript.crockford.com

21–30 of 31 posts

Re: Code Conventions for the JavaScript Programming Language

#21
post #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.

And if you turn on wrap-to-screen? If you've got line numbers and/or overflow indicators, wrapped text is easy to read.

Re: Code Conventions for the JavaScript Programming Language

#22
post #21
post #16

Earlier quoted context omitted.

> 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.

And if you turn on wrap-to-screen? If you've got line numbers and/or overflow indicators, wrapped text is easy to read.

I do have both line numbers and overflow indicators on, but I still find wrapped text (especially if an identifier is broken into two) harder to read.

Re: Code Conventions for the JavaScript Programming Language

#23
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");

I'd do this:

    document.getElementsByClassName("externalLinkBig")[0].setAttribute(
        "class", "externalLinkSmall"
    );

Re: Code Conventions for the JavaScript Programming Language

#24
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…

I can easily read code that's written with 2, 4, or 8 space indentation. I can't read code that's written with 2, 4, or 8 space indentation at the same time.

The most important part about code conventions is that you have them. It really doesn't matter what they are. In fact, I wish fewer styleguides would pretend to be right and more would just acknowledge that they're simply whatever the originator prefers. But it's still very important that everyone agrees to follow them, even if they disagree with some of the individual aspects.

Re: Code Conventions for the JavaScript Programming Language

#25
post #18

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…

"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 t…

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?

I can't speak for Crockford, but I would note that "function foo() = {}" is equivalent to "var foo = function () {}", so it may be for the same reason for declaring global variables up top.

You simply don't document the "private" properties. Pretending JavaScript is more robust than it is helps no one and wastes memory.

I don't think we're talking about the same thing. I'm talking about private variables, the same way they are used in other programming languages: variables that cannot be accessed from outside the object. When you try to access private variables in other languages it throws an error, and you want it to throw an error, that's why you make it private. You don't want it accessed. Crockford shows how you can do that in js. Consider this version of the code you gave:

function Point(x, y){ this._x = parseInt(x,10); this._y = parseInt(y,10); var _private = 'foo' } 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) }

var myPoint = new Point(100,50); alert(myPoint._x); alert(myPoint._private);

The last alert will show 'undefined', that's intentional.

Const is not supported in IE (https://developer.mozilla.org/En/Core_JavaScript_1.5_Referen...), and wasn't originally supported in js.

I've already pointed out that there is already a common, testable convention in place: if((a = b))

Avoiding assignments in conditionals is general advice in more than just one language. Besides here's what Mozilla says about it:

assignment in a conditional (Note: you can suppress this warning by including an extra set of parentheses around the assignment) (https://developer.mozilla.org/en/New_in_Rhino_1.6R6)*

Also:

It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:*

If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment.

In other words you can put () around the assignment, but that doesn't mean you should or that it's a best practice.

Crockford literally wrote the book on JavaScript, and I've seen his defense of some of his coding conventions in various talks, so I'm inclined to give him the benefit of the doubt. If you disagree with some of them, hell, email the guy. He might explain it in better detail.

Re: Code Conventions for the JavaScript Programming Language

#26
post #20
post #17

Earlier quoted context omitted.

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

A bit off topic, but double underscores don't actually make members in Python truly private, but mangles the attribute name to prevent you from accessing it unless you really need to: http://docs.python.org/tutorial/classes.html#private-variabl...

    >>> class Foo(object):
    ...     def __do_something(self):
    ...         print 'something was done'
    ... 
    >>> f = Foo()
    >>> f.__do_something()
    Traceback (most recent call last):
      File "", line 1, in 
    AttributeError: 'Foo' object has no attribute '__do_something'
    >>> f._Foo__do_something()
    something was done

Re: Code Conventions for the JavaScript Programming Language

#27
post #18

Earlier quoted context omitted.

"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 t…

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? I can't speak for Crockford, but I would note that "function foo() = {}" is equivalent to "var foo = function () {}", so it may be for the same reason for declaring global variables up top. You simply don't document the "private" properties. Pretending JavaScript is more robust than…

"Const is not supported in IE [...] and wasn't originally supported in js."

Which is an irrelevant point anyway since it still doesn't justify hijacking an already commonly accepted convention for some other purpose.

"In other words you can put () around the assignment, but that doesn't mean you should or that it's a best practice."

The point is that the meaning is clarified by using the convention.

"It is advisable to not use simple assignments in a conditional expression,..."

I would not presume to know what level of brevity is desirable for a developer in a given situation. Conventions like the one mentioned are available for clarification of such constructs.

"Crockford literally wrote the book on JavaScript, and I've seen his defense of some of his coding conventions in various talks, so I'm inclined to give him the benefit of the doubt."

Accepting an argument based on perceived authority is a logical fallacy. "the book on JavaScript" has some questionable things as well I hear:

    Function.prototype.method = function(name, func) {
        this.prototype[name] = func;
        return this;
    };
I do truly hope people don't consider such examples a good idea.

Re: Code Conventions for the JavaScript Programming Language

#28

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.

There are arguments for and against tabs and spaces.

... and if you don't want to rehash those arguments, jwz has a nice summary: http://www.jwz.org/doc/tabs-vs-spaces.html

Re: Code Conventions for the JavaScript Programming Language

#30
post #28

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.

There are arguments for and against tabs and spaces. ... and if you don't want to rehash those arguments, jwz has a nice summary: http://www.jwz.org/doc/tabs-vs-spaces.html

I found that summary wholly unconvincing, and very disparate from how I might summarize the arguments.

I guess that's just how these things go.

Post reply on HN