1

In JavaScript, are there any downfalls to declaring multiple variables on one line that depend on one another (besides readability)?

var string="Hello World",length=string.length,i=string.indexOf("World");

I have a string, then I get its length and then I also search for a string in it.

As long as they are in the right order, I should be fine, right? No strange behavior occurs in different JavaScript compilers?

user215997
  • 1,267
  • 2
  • 12
  • 12

3 Answers3

2

No, that is fine. But more readable (and actually you should favor readability) would be:

var string = "Hello World",
    length = string.length,
    i = string.indexOf("World");

It is also easier for your to maintain the code. Don't minify / compress your code manually, there exist tools for that.

Community
  • 1
  • 1
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Statement execution occurs from one line to the next, ";" tells it to start on the next statement (ie. the next line). There should be no issue at all.

John
  • 1,530
  • 1
  • 10
  • 19
-1

Well, it's really inadvisable to write code where order matters. It's against best practice. Secondly, only the first variable will be local to the function in which you're declaring it. The other two variables will be global, opening you up to the possibility of junk or clobbered data.

Srdjan Pejic
  • 8,152
  • 2
  • 28
  • 24
  • 3
    That is not true. All variables will be local. You confuse this statement with `var foo = bar = 42;` where `foo` is local and `bar` will be global. – Felix Kling Mar 08 '11 at 20:31