0

I already know the difference between using "var" and not using "var" to declare a Javascript variable. Using "var" ensures that the variable exists as a distinct entity strictly within the local scope of the code block, whereas not using "var" would effectively make the variable global. I also know that if you declare a variable at the global level, it doesn't matter whether you use "var" or not.

So my question is, is there ever a situation where it would be better to NOT declare a variable using "var"?

So far, I'm under the impression that it never hurts to always use "var" to declare a variable. Are there exceptions to this?

drumwolf
  • 399
  • 1
  • 4
  • 16
  • See http://stackoverflow.com/questions/1470488/difference-between-using-var-and-not-using-var-in-javascript – devnull May 23 '13 at 05:01
  • Using `var` to create a global variable (which creates a property of `window`) will make it undeletable. For example, you could use `a = 2;` and then `delete window.a;` (or `delete a;`) and it will work. As soon as you use `var`, neither of those work. And of course, that setting can be customized with `Object.defineProperty()` – Ian May 23 '13 at 05:49

4 Answers4

3

Not really. In fact, in strict mode you cannot declare a variable without a scope or a var. So, if you were trying to declare a global variable you must do something like window.foo = "bar";

Granted, window.foo is really "set a property on the window object".. so it's not even really initializing a variable.

Stephen
  • 5,362
  • 1
  • 22
  • 33
1

Your question assumes that you do have control over whether your variable declaration is the "initial" declaration. If you do have that control, then there is never a reason not to use var except when you are working inside of a function and specifically want to access a global variable and not create a local variable. In that case you must not use var or else the variable will become a local variable and you can never access the global variable with the same name from within that function.

When you are using variables in the global scope, you are technically making an error if the same variable name is declared twice using var. There is no way to control this from happening sometimes, which is why you will run into situations where you "can't" use var.

Update: the type of error I am referring to is something like this: error: Identifier 'x' has already been declared

This doesn't happen anymore (thankfully). It happened way too often in the late 1990s when JavaScript was new. Perhaps it was an error of the browser implementations. At at rate, don't worry about redeclaring variables with var anymore. (Redeclaring variables with let is still not permitted. For the let keyword, Redeclaring the same variable within the same function or block scope raises a SyntaxError.)

Let me explain the history of the practice behind my word "can't":

Starting with the old-fashioned "Hit-o-Meter" scripts, JavaScript programmers started noticing that their scripts generated error messages (for anyone looking at the console) when used in the "wild" when many different script elements in the page might use the same global variables. The solution to avoid the errors from showing up was to simply not declare the variable. (A warning would show up when the variable was implicitly declared by the first assignment to it, but all the other errors that happened by multiple variable declarations in many places on the page would be gone. So it was a question of a lesser evil versus a greater evil.)

If you have full control over all the scripts in the page, then you will have full control as your phrase says, "initially declaring a JavaScript variable." For example, you can use var when declaring a global variable in the top script, but not use var when using the same variable in another script element later in your page.

If you have no way of controlling whether a variable with the same name might have been declared before, and if you don't want to commit the possible evil of using a global variable which has never been initialized even by a prior script element, then you have the option that I use of using properties of "self" or other convenient window or document properties. For instance, I will write self.variable = 1, which will be free of any problems associated with redefining a variable. There are no errors or warnings generated regardless of whether this variable is being used for the first time or being re-used by my script after already being used by another script on the page.

(Note: currently self and window are considered to be equivalent, but there was a time in the days of framesets where it was considered better style to use self to store any global variables/properties--and it also saved a tiny bit of code.)

Joseph Myers
  • 6,434
  • 27
  • 36
  • "*you are technically making an error if the same variable name is declared twice using var*" - um, no. `var` does support re-declarations, and that's indeed why it *always* should be used especially when you don't know whether it's the initial usage or not. – Bergi Mar 02 '18 at 01:13
  • @Bergi I have been writing JavaScript since the first edition. I have personally seen the errors happen, something similar to "Uncaught SyntaxError: Identifier 'x' has already been declared". Today, this is not an issue, so my information is out of date. – Joseph Myers Mar 05 '18 at 15:38
  • Ok, I'm too young for that - started with ES3 and never seen that error on a `var`. Thanks for the update! – Bergi Mar 05 '18 at 16:26
0

If you're in the global scope then there's no difference.

If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).

If you're not doing an assignment then you need to use var:

var x; // Declare x
Subedi Kishor
  • 5,906
  • 5
  • 35
  • 53
-2

Sometimes you have to not use var, to access or change certain global (window.variable) variables.

NoBugs
  • 9,310
  • 13
  • 80
  • 146