0

When writing a Javascript function I have always made the first assignment to a variable with var as in

var x = 1;

Later x may be something else. Should I write

if (something ) {
x = 2;}

or

if (something) {  
var x = 2;}

If you could say why that would help.

Betty Mock
  • 1,373
  • 11
  • 23
  • 1
    MDC is a good place to start: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var – Matt Ball Nov 19 '13 at 04:01
  • These previous answers should sort you out: http://stackoverflow.com/questions/2485423/javascript-is-using-var-to-declare-variables-optional http://stackoverflow.com/questions/500431/javascript-variable-scope – JMP Nov 19 '13 at 04:05
  • var is scoped per function. JavaScript doesn't have block scope. It's best to declare variables as close as where you use them but in a function that's at the start of a function: `var a;` even though you're not going to us it until the end of a function it is good for better readability. ECMA 5 has block scope and new Firefox has it as well: `for(let i = 0....` the variable i is only available in the for loop. – HMR Nov 19 '13 at 06:27
  • http://www.youtube.com/watch?v=ya4UHuXNygM 2:40 – HMR Nov 19 '13 at 06:30

2 Answers2

5

You shouldn't use the var keyword if you're changing the value of a variable that's already been declared.

So:

var x = 1;

if(something) x = 2;

If the test was that simple, you could also write it like this:

var x = something ? 2 : 1;

It's also got to do with scoping. A new scope is created within functions.

For example:

var x = 1;

function myFunction(){
  var x = 2;  
}

myFunction();

console.log(x); // 1

Whereas, if you omitted the var keyword within the function, you would be altering the value of the x variable in the outer scope and the console.log(x) would show 2.

ahren
  • 16,803
  • 5
  • 50
  • 70
  • 4
    Congratulation to 10K! – some Nov 19 '13 at 04:02
  • @ahren Thanks for the clear explanation. I ramp up my language knowledge a little at a time, and straightening out this one issue is a good step (even tho my functions are working). My conditions are sometimes rather complex, but not always and I didn't know about the shortcut code. – Betty Mock Nov 20 '13 at 00:14
  • You're welcome @BettyMock - that's exactly what this forum is for! – ahren Nov 20 '13 at 00:16
1

In code that simple, it actually makes no difference whatsoever to the JS interpreter.

For the sake of all who have to read the code, however, it is best to declare variables once at the top of the scope in which they are needed. This helps make it very clear to all who work with the code where a variable is scoped. It also helps you avoid running into confusing issues caused by the JavaScript hoisting mechanism (which mechanism is actually the very reason it doesn't matter in your code).

JAAulde
  • 19,250
  • 5
  • 52
  • 63