r/javascript • • Feb 23 '13

Common JavaScript "Gotchas"

https://github.com/stevekwan/best-practices/blob/master/javascript/gotchas.md
16 Upvotes

50 comments sorted by

View all comments

8

u/mirion Feb 23 '13 edited Feb 24 '13

OP: At least you recommended that book at the end. That is the sole most useful piece of information in that entire article, and the best resource for anyone learning Javascript. I require any new Javascript programmer on my team read it before starting JS development.

The second most useful thing you could have done is explained to new programmers the use of 'use strict'. It's not always the solution, but it damned well prevents a lot of what you're describing.

edit -- Several sections below have been edited thanks to feedback from /u/brianloveswords and /u/mikrosystheme


Your discussion of variables is flawed, and lacking in detail. The most important thing you could have discussed about variables is that if they are defined anywhere in a scope, they are accessible anywhere in that scope. For example:

function () {
    var x = 10;
    x += y;

    var y = 5;
}    

At the end of execution, x will be NaN and y will be 5. Variable declarations get hoisted, but instantiation does not, so the interpreter sees this (effectively):

function () {
    var x, y;
    x = 10;
    x += y; // y is undefined at this point

    y = 5;
}

This code is completely valid in JS, because "y" is accessible to the entire scope of its function. Because of this, any sane or informed discussion of Javascript variables must include an explanation of this, and a strong recommendation to define all variables at the top of a function (since they work as if they were all defined there anyways). Failing to explain this is a major failing.

The reason that a variable defined without a var becomes global scoped is because variables default to being defined in the widest scope possible. Thus, defining with a var is necessary because it limits the scope of a variable.


Your point about function declarations is what I generally advise people, but misses out on the most important part of the whole thing: all functions are declared as variables, and can be set or accessed as such. The best reason, IMO, for declaring them as "var foo = function () {};" is to make explicit the nature of the function to the programmer -- programmers coming over from other languages will see this an immediately understand the things you can do to it, whereas seeing the "function foo () {}" declaration style could lead new JS coders to believe (incorrectly) that the function is immutable.


There are some extremely good reasons to have "this" refer to the calling context. It can lead to massive confusion in new coders, and so, yes, I would agree that perhaps new programmers should get more comfortable with closures before doing heavy work with "this". However, avoiding the use of 'this' most likely means that you're overusing closure scoping to crib in a 'that' variable, or else you're not going very OO heavy in your code. While both are entirely valid styles of coding JS, they also drift further away from more standard practices, and can make your code base even harder for new programmers to understand.


I'm a little disappointed that you mentioned OOP, constructor, and prototype, then skipped past providing any examples at all. Your comments about 'this' seem to imply that you have a strong opinion about how these should work, but without actually showing people how you think it should be done, you completely miss a great opportunity to demonstrate proper usage.


Javascript does not treat newlines as a text separator. JS parsers use Automatic Semicolon Insertion to handle cases where there is no semicolon at the end of a line, but, as per the creator of Javascript:

ASI is (formally speaking) a syntactic error correction procedure. If you start to code as if it were a universal significant-newline rule, you will get into trouble.

A classic example of where this is a problem:

a = b + c
(d + e).print()

Similar hazards arise with [, /, and unary + and -. Remember, if there wasn’t an error, ASI does not apply.

For more concrete examples, see the Google Javascript style guide.

2

u/stevekwan Feb 23 '13

Wow! A great peer review and tons of good advice here. Thanks mirion, I will definitely take these into account.

1

u/[deleted] Feb 23 '13

Thank god for that guy. I didn't want to type all of that up on my phone. You both do one thing any other JS dev will hate you for though: Allman Style indentation.

var x = 1;
function allman()
{
     x++;
}

The { on another line is BAD in scripting languages! Because one could comment out or delete a line accidentally, and it's still valid code throwing no errors:

var x = 1;
//function allman()
{
     x++;
}

On the other hand, this would vomit all over:

var x = 1;
//function allman() {
     x++;
}

This is why KNF style (shown above) is preferred for JavaScript. The only language I can think of off the top of my head where Allman style is the preferred common-practice is C#. But you'd have less problems in any compiled language like that, because the compiler is going to watch your syntax pretty closely. EDIT: Banner style is used a lot too.

1

u/mirion Feb 24 '13

I wrote my post almost entirely by copying his code. While I didn't refer to it by name, my last two sections are referencing the problems that can happen when using Allman.