r/javascript • u/stevekwan • Feb 23 '13
Common JavaScript "Gotchas"
https://github.com/stevekwan/best-practices/blob/master/javascript/gotchas.md8
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:
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
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/stevekwan Feb 23 '13
I am positive this is going to be heavily disagreed with...but I really like Allman. :)
I like it for two reasons:
First, I just like the Gestalt of it. I find code a lot more scannable when the squigglies line up nicely, especially in languages like JavaScript where you can have a ton of nesting.
Second, it forces me to write my code in such a way that whitespace becomes irrelevant. I can never get away with something like this:
return { foo: "foo" };And so I am forced to name things appropriately, which I prefer.
But I completely understand that I am in the minority on this, and I would never attempt to fight this battle. :)
0
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.
4
Feb 23 '13
Your example,
function () { var x = 10; x += y; var y = 5; }is potentially misleading. At the end of execution,
xwill beNaNandywill be5. 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; }0
u/mikrosystheme [κ] Feb 24 '13
Please, show me a circumstance where your last paragraph is true.
1
u/mirion Feb 24 '13 edited Feb 24 '13
How about an article talking about semi colon use by the guy who wrote JavaScript? Would that be good enough?
http://brendaneich.com/2012/04/the-infernal-semicolon/
edit google gives examples, too:
http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml#Semicolons
1
u/mikrosystheme [κ] Feb 24 '13
I'm not arguing if relying on ASI is good or bad. I just asked you to provide an example where what you wrote is true (because it is not AFAIK).
1
u/mirion Feb 24 '13
The google link provides examples.
1
u/mikrosystheme [κ] Feb 24 '13 edited Feb 24 '13
You wrote that:
$('button').click
// ...
(
function () {
window.alert(clickmessage);
}
);
... Rather than calling the "click" function with that function as an argument, the parser could see you creating a new scope (by encapsulating the function in '()'), and then creating an anonymous function.I really like to know in which circumstances what you wrote is going to happen. Can you please provide me with a reference or with a working example that demonstrate it?
1
u/mirion Feb 24 '13
Ah, I see what you mean. You are correct -- his code as written would not exhibit the problem I described. I'll update the comment with a link to the examples from the google webpage. My intent was to discuss the problem with the syntax, not to demonstrate an actual example of the result. Why? Because it's supposed to be a topic for beginners, and the explanations for why some of these occur is not.
3
u/wkdown Feb 23 '13
Quick question: which is the 'proper' way to instantiate an object?
var obj1 = {};
or
var obj2 = new Object();
Both return [object Object] and typeof "object". Is one better than the other?
6
u/radhruin Feb 23 '13
There is no semantic difference between {} and new Object(). The literal, however, is easier to optimize and therefore often faster. The literal is also more flexible as it allows additional properties to be added. Always use the literal IMO.
5
u/YorickA Feb 23 '13
Not to mention it's more readable.
1
Feb 23 '13
Not to mention
new Object()can be broken by any malicious ding-dong's script you link like so:function Object() { this.x = 'wee'; }Using the literal is always the best call.
3
3
1
u/youngsteveo Feb 23 '13
Some jsPerf tests on the many ways to construct an object: http://jsperf.com/object-create-vs-constructor-vs-object-literal/53
0
u/stevekwan Feb 23 '13
I'd avoid using new Object(). {} is preferred. The only reason I used new Object() is because I felt it would be more understandable to people coming in from another language.
2
u/dangoodspeed Feb 23 '13
He says you should never ever have a global variable or global function. Do other people agree with that?
1
u/stevekwan Feb 23 '13
Sorry, I should make that clear. Globals are unavoidable to some degree, unless you are assigning no names to anything at all. :) But I try to use globals only where it makes sense, eg for namespaces and other top-level containers.
2
u/kmillns Feb 23 '13
I'd say you should never have an implied global. If you're going to attach something to global, make it clear that you're doing it on purpose:
(function (global) { global.foo = 'foo'; })(window);Also, something that he doesn't note, but that's important if you're writing production code, is that implied globals (like his examples) are syntax errors in strict mode.
0
u/mirion Feb 23 '13
This. Definitely this.
2
u/rabidcow Feb 23 '13
Sure, you could use
this:(function(){ this.foo = 'foo'; })();2
u/mirion Feb 23 '13
Sigh. I should know better than to use the word 'this' in a javascript thread.
4
2
1
Feb 24 '13
You should know better than to use the word 'this' in any thread. There's an up arrrow button next to the post that does that.
2
u/mirion Feb 23 '13
No, lol. It shouldn't be abused, but it is extremely useful in limited circumstances. You can't, for example, use write library code without it.
4
u/colordrops Feb 23 '13
This person does not yet grock JavaScript. He seems to think that a lot of the sensible behavior of JavaScript is "bizarre".
JavaScript has several styles of variable and function declaration because it wants to both cater to new programmers used to imperative style programming while at the same time allowing programmers to work withing the functional paradigm. It successfully supports both.
Then he talks about how JavaScript is unlike other languages, where objects refer to parent objects when the current object does not contain the referenced property. WTF is he talking about? This is how most OO languages work.
Then he says that the fact that you can do things in different ways in JavaScript is because it is poorly designed. No, it is because he doesn't get JavaScript.
-2
u/stevekwan Feb 23 '13
I understand why JavaScript has multiple ways to do the same thing, and I understand that this was an attempt to increase adoption. Unfortunately it results in a language that is somewhat schizophrenic in how it is used. The vast majority of engineers I've seen who get into JS expect it to behave like C++, Java or PHP, largely because of the syntax that is used.
JavaScript is a great language to develop in, but it is far from perfect. I'm hardly the only one who is saying this. Heck, Crockford wrote a whole book about it. If you don't agree with me, perhaps you'll find it easier to agree with him.
If you want to message me the line number in question that you had problems with re: object hierarchies, I'm happy to clean it up.
18
Feb 23 '13
Valiant attempt, but there are a number of issues with this post.
Author talks about the different ways to declare a function, but doesn't actually come out and say "function statement vs function expression", and doesn't mention hoisting of function statements. He also recommends always using function expressions because of "syntax problems once you get into closures", but never brings up the potential syntax problems.
Telling people to avoid
thisis bad advice. Users will run into code that usesthisand understanding its semantics is fundamental to understanding the OO parts of JavaScript.In the section about
this, author fails to mention the important pitfalls: failing to usenewwith a constructor and changing scope due to nested functions.Using
var x = new Object();is nonidiomatic;var x = {};is the prefered way to instatiate a new object.Author answers his own question to why JavaScript has so many ways to do different things with "Because JavaScript is a poorly designed language in a lot of ways." I bristled at this statement and it took a bit of reflection to understand why since I don't entirely disagree. My problem is that I don't think the author is in a qualified position to make that statement. Saying something is "poorly designed" assumes knowledge of the design goals and in this case I don't believe the author fully understands them. It reminds me of how junior developers often say "this sucks" rather than "I don't understand this".
And a couple of nitpicks:
I dislike Allman style indentation (and it's fairly nonidiomatic in JavaScript).
Author should use
jsdeclaration around his code blocks for enhanced readability, e.g.:```js var radLevel = "maximum"; ```
This will make github render the code with js syntax highlighting.
4
u/kmillns Feb 24 '13
I dislike Allman style indentation (and it's fairly nonidiomatic in JavaScript).
And it's not just non-idiomatic. You either have to have inconsistent braces and indentation (bad) or you risk errors (worse).
The go to example problem with Allman style indentation is:
return { foo: 'foo' };Which returns undefined.
18
Feb 23 '13
This is possibly the worst blog entry I've ever read on JavaScript. It's downright incorrect in most cases and full of unsubstantiated opinion.
4
Feb 23 '13
Can you explain why is the worst? He explains some best practices in a clear way.
-1
u/totemcatcher Feb 23 '13
One of the problems I noticed (among many discussed in this thread) is the function declaration no-no. It says never declare globally. But it doesn't discuss namespacing in javascript and how you pretty much have to use that function declaration type when namespacing.
4
4
Feb 23 '13
Funny that he mentions Crockford's book, yet his whole post is basically JAVASCRIPT AMIRITE??? Without any kind of demonstrated understanding of how it works. In fact, one of Crockford's first chapters is devoted to calling people like this author out as developers trained in other languages shoving round pegs into a square hole.
0
u/mergeset Feb 23 '13
Poorly written, a little pretentious, and in some cases just outright wrong. That's a downvote from me.
0
Feb 23 '13
[deleted]
4
Feb 24 '13
To further elaborate:
var myFunction = function myFn(arg1, arg2) { console.log(arg1, arg2); }; myFunction('foo', 'bar'); // -> foo bar myFn('foo', 'bar'); // Reference Error: myFn is not definedTo someone that didn't know better or just didn't scan the line properly this can be a frustrating gotcha to catch.
20
u/youngsteveo Feb 23 '13
"If you are new to JavaScript, I suggest avoiding the this keyword until you get comfortable with the basics of the language." This is terrible advice. If all beginners started learning Javascript by getting a firm grasp of
this, there would be a lot fewer mistakes and misunderstandings down the road.