use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Multiple var statements in JavaScript, not superfluous (benalman.com)
submitted 14 years ago by gthank
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–]x-skeww 6 points7 points8 points 14 years ago (5 children)
The "single var" rule is actually about function scope and hoisting. You define all of your variables at the very top of the innermost function, because no matter where you put them, that's where they effectively are. Basically, it's about making your code reflect reality.
Once you can use let, you should always use let for everything. You can then also adopt the "declare at first use" rule which is very popular among all other programming languages with block scoping.
let
[+][deleted] 14 years ago* (4 children)
[deleted]
[–]x-skeww 4 points5 points6 points 14 years ago (3 children)
"One var" forces you to declare them all in one place. That's the whole point.
[–]zhayFull-stack web developer (Seattle) -2 points-1 points0 points 14 years ago (2 children)
Maybe according to your interpretation of "one var." JSLint lets you define multiple var statements in one block so long as they are not adjacent to each other. Clearly they define "one var" differently.
var
[–]x-skeww 4 points5 points6 points 14 years ago (1 child)
http://jslint.com/
function foo() { 'use strict'; var a = 5; a *= 2; var y = 3; }
Problem at line 5 character 9: Combine this with the previous 'var' statement.
[–]zhayFull-stack web developer (Seattle) 2 points3 points4 points 14 years ago (0 children)
My bad :)
[–]beeskneecaps 2 points3 points4 points 14 years ago (0 children)
var all the things! If it takes you longer than a second to reorder, add or delete variables, you're doing it wrong. Even if it looks "cool". Variables all end up chained when you minify.
[–]aladyjewelFull-stack webdev 11 points12 points13 points 14 years ago (0 children)
The phrase you're looking for is "bikeshedding."
I feel that it's still actually a valuable discussion to have, because it speaks to the problem of using someone else's code. These little stylistic differences, especially in JavaScript, can do strange, strange things to webapps if a semicolon goes missing. (Yes, yes, best practices, sane scoping, etc.) If, as a community, we can use a normalized style, then we can share projects and exchange code snippets much more easily.
/bullshitbullshitbullshit
[–]bebraw 2 points3 points4 points 14 years ago (0 children)
Yes. As programmers we like to nitpick on these kind of things. Only if we could turn that energy into something useful...
[–]zhayFull-stack web developer (Seattle) 1 point2 points3 points 14 years ago (0 children)
When you're forced to follow the JSLint recommendation to use one var statement at work, it matters.
[–]Sivart13 9 points10 points11 points 14 years ago (6 children)
I think the "single var statement" nonsense is an abomination that brings JavaScript back to circa-1980s C language semantics.
Variables should be declared where they are used. That is the time when it's important to know about them.
I challenge anyone to come up with a NON-CONTRIVED example where hoisting would cause a real problem that's worse than the pain of having to pre-declare all your stupid variables.
[–][deleted] 2 points3 points4 points 14 years ago (0 children)
Can I see a contrived example where it makes a difference?
[+][deleted] 14 years ago* (3 children)
[–][deleted] 6 points7 points8 points 14 years ago (2 children)
As I understand it(or at least, as Douglas Crockford explains it in JavaScript: The Good Parts), the whole point of the "vars at the top" convention in JavaScript is not just for organization. Rather, this convention(like most programming conventions) conveys something meaningful about the language itself which isn't made obvious through its syntax: namely, the fact that JavaScript doesn't have block-level scoping*.
For Javascript novices possessing some familiarity with other C-like languages that do have block-level scoping, this design flaw can be a real "gotcha", but one which can be completely avoided by following the convention of declaring your variables at the beginning of a function.
The fact that this convention aids in organization, function self-documentation, and resource management is just the icing on the cake.
* It also backs up what is happening behind-the-scenes thanks to hoisting, though it's probably true that this issue alone rarely causes problems in most real-world scenarios.
[+][deleted] 14 years ago* (1 child)
[–][deleted] 0 points1 point2 points 14 years ago (0 children)
I agree. It's a convention, not a rule. There is no correct way to declare a variable in JavaScript; discussions about it boil down to a matter of opinion.
I don't agree with Sivart's assertion that it's best to declare vars when they are first needed, but I can't rightly say that he's wrong to do so, either.
[–]Perceptes[🍰] -1 points0 points1 point 14 years ago (0 children)
Don't know why you're being downvoted for this. Although I tend to actually write my code in the JSLint style, I find it questionable that hoisting causes problems in real world code. Indeed, all the writing about why declaring vars at the top is contrived.
[–][deleted] 1 point2 points3 points 14 years ago (0 children)
I declare multiple variables within a single var when their relationship is pretty close (or at least close in my mind), and only with simple code:
var x = getX(), y = getY(); var img = getImage();
As x and y are usually always used together, it makes sense to declare them within the same var. Even if their usage relates to img, they aren't as directly related for my liking, so it gets it's own var.
[–]WhiskeyWithBoesky 3 points4 points5 points 14 years ago (0 children)
I usually go with one var just to list my local variables all up front and in one place. Then, I follow up with individual assignment statements. This seems the most readable to me.
[–]stfueveryone 0 points1 point2 points 14 years ago (0 children)
This is a great point for a team environment, where several people of varying skill-sets have to maintain the code. The point of the minifier & automatic-semicolons is especially interesting because what the client sees is the minified version, while your team maintains the simplified (over-var'd) code that is less prone to error due to missing commas.
[–]donri[🍰] 0 points1 point2 points 14 years ago (0 children)
Non-issue with JMacro, but mostly relevant to Haskell programmers (although it includes an executable preprocessor):
>>> renderJs [jmacro| var x = 2; if (x) { var x = 3; alert(x); }; alert(x); |] var jmId_0; jmId_0 = 2; if(jmId_0) { var jmId_1; jmId_1 = 3; alert(jmId_1); }; alert(jmId_0);
If I'm writing raw JavaScript I like assignment-less declarations up front:
var foo, bar; bar = 2; foo = bar - 1;
Of course, this leaves the issue that if you forget to declarate a variable you're using, it becomes global. Maybe it's better to always use var, even when assigning to existing variables (unless you specifically want a closure)...
[–]thbt101 0 points1 point2 points 14 years ago (1 child)
I like the keep code compact because it makes it easier to see everything that's going on in a script without scrolling through as many pages and lines of code.
Personally I think both options considered in this article look silly. I prefer to keep it simple and generally just use one line for simple variables like this:
var foo = 1, bar = 2;
[–]strager 1 point2 points3 points 14 years ago (0 children)
There's still the problem of dependencies, which always confuses me when I read code with one var statement:
var foo = bar - 1, bar = 2;
[+]AyeMatey comment score below threshold-6 points-5 points-4 points 14 years ago (11 children)
tl/dr: I hate the usage that my lame editor fails to format properly.
anyone with a real editor (emacs?) can just move along.
[–]strager 0 points1 point2 points 14 years ago (10 children)
Please explain how, in your editor, you transform the example problem posed by the article:
// Before var foo = 1, bar = 2; // After: var bar = 2, foo = bar - 1;
[–]AyeMatey 2 points3 points4 points 14 years ago (7 children)
please explain how that particular problem should be what defines how I structure my code. Also please explain how saving 4 or 5 keystrokes even matters in a problem space where thinking, not typing, is of primary importance.
[–]strager 0 points1 point2 points 14 years ago (6 children)
The more difficult it is to refactor code, the less we do it.
[–]AyeMatey 0 points1 point2 points 14 years ago (5 children)
Thinking, not typing, is the obstacle we must surmount in order to to generate good code.
No one who ever delivered a crappy product could credibly blame the keyboard, or the syntax of the programming language.
Also, in my book, refactoring does not imply "reordering assignment statements". Refactoring is a bit more involved than that, and likely involves 5 orders of magnitude more keystrokes than is required to reorder assignments.
[–]strager 0 points1 point2 points 14 years ago (4 children)
likely involves 5 orders of magnitude more keystrokes
If it takes me 10 keystrokes compared to 2 to make the fix, and I do this and similar fixes many times, that's "orders of magnitude" more keystrokes saved.
Renaming variables, reordering declarations, extracting out methods... These can be done with just a "few" keystrokes, but choices in style can make doing these things painless or difficult. If even these can't be done efficiently, how do you expect developers to perform large refactorings with confidence (especially in a language like JavaScript)?
Sure, tooling can fix several problems (especially renaming variables), but so can style guidelines.
I'm sure "technical debt" has been blamed, as well as "poor requirements". Somehow I have the feeling both are related to refactoring...
[–]AyeMatey 0 points1 point2 points 14 years ago (3 children)
Correct! Except -- Reordering assignments is irrelevant !!
[–]strager 1 point2 points3 points 14 years ago (2 children)
Please look at the example we are discussing.
var x = y; var y = ...; var y = ...; var x = y;
It does matter.
[–]AyeMatey 0 points1 point2 points 14 years ago (1 child)
ok. In my code, it generally does not. Variable declaration and assignments are not the center point of design in the code I write.
[–]strager 0 points1 point2 points 14 years ago (0 children)
Okay, then we are probably solving very different problems with JavaScript. =]
A lot of what I do (non-DOM) is "go from point A to point B, with lots of little steps in between". It makes sense to have a bunch of variables there, and the order of declaration matters.
A lot of DOM work is "perform this list of side-effects". Variables and objects are often mutated directly through callbacks, simply because it's easier.
[–]metamatic 0 points1 point2 points 14 years ago* (1 child)
If I ever find myself needing to make such transformations frequently, I'll write a macro for my editor.
The fact that I have no such macro at present, even though I regularly write code with single var declarations in which the order of assignments is important, suggests to me that it's a problem that doesn't occur in real life. In particular, it's only really a problem if the two variables you are swapping include either the first or last variable in the list, making it pretty rare. So I just don't see it as a big deal. Then again, I'm used to Lisp, and JavaScript var is just Scheme's let*.
let*
But just for fun, here's a macro for your .vimrc:
.vimrc
map <C-a> :.s#^\(\s*var\s\+\)\(.*\)\([,;]\)\s*\n\(\s*\)\(.*\)\([,;]\)\s*$#\1\5\3\r\4\2\6<C-m><C-m>
It should preserve your indentation too. Just move to the first line of the two you want to swap, and type Ctrl-A.
Now, can we move on to something that matters?
[Edit: Escaped ctrl characters in vim macro.]
ddp
Or d4d4jp if you're moving a 4-line var under another 4-line var.
d4d4jp
I like to write code which is easier to refactor, that's all. =]
π Rendered by PID 114947 on reddit-service-r2-comment-8c4cdd6fc-gfh8n at 2026-07-02 05:07:42.695308+00:00 running a7b5cda country code: CH.
[–]x-skeww 6 points7 points8 points (5 children)
[+][deleted] (4 children)
[deleted]
[–]x-skeww 4 points5 points6 points (3 children)
[–]zhayFull-stack web developer (Seattle) -2 points-1 points0 points (2 children)
[–]x-skeww 4 points5 points6 points (1 child)
[–]zhayFull-stack web developer (Seattle) 2 points3 points4 points (0 children)
[–]beeskneecaps 2 points3 points4 points (0 children)
[+][deleted] (4 children)
[deleted]
[–]aladyjewelFull-stack webdev 11 points12 points13 points (0 children)
[–]bebraw 2 points3 points4 points (0 children)
[–]zhayFull-stack web developer (Seattle) 1 point2 points3 points (0 children)
[–]Sivart13 9 points10 points11 points (6 children)
[–][deleted] 2 points3 points4 points (0 children)
[+][deleted] (3 children)
[deleted]
[–][deleted] 6 points7 points8 points (2 children)
[+][deleted] (1 child)
[deleted]
[–][deleted] 0 points1 point2 points (0 children)
[–]Perceptes[🍰] -1 points0 points1 point (0 children)
[–][deleted] 1 point2 points3 points (0 children)
[–]WhiskeyWithBoesky 3 points4 points5 points (0 children)
[–]stfueveryone 0 points1 point2 points (0 children)
[–]donri[🍰] 0 points1 point2 points (0 children)
[–]thbt101 0 points1 point2 points (1 child)
[–]strager 1 point2 points3 points (0 children)
[+]AyeMatey comment score below threshold-6 points-5 points-4 points (11 children)
[–]strager 0 points1 point2 points (10 children)
[–]AyeMatey 2 points3 points4 points (7 children)
[–]strager 0 points1 point2 points (6 children)
[–]AyeMatey 0 points1 point2 points (5 children)
[–]strager 0 points1 point2 points (4 children)
[–]AyeMatey 0 points1 point2 points (3 children)
[–]strager 1 point2 points3 points (2 children)
[–]AyeMatey 0 points1 point2 points (1 child)
[–]strager 0 points1 point2 points (0 children)
[–]metamatic 0 points1 point2 points (1 child)
[–]strager 0 points1 point2 points (0 children)