53

In this tutorial there is written:

If you redeclare a JavaScript variable, it will not lose its value.

Why should I redeclare a variable? Is it practical in some situations?

thank you

1

8 Answers 8

63

It's nothing more than a reminder that if you do this:

var x=5;
var x;
alert(x);

Result will be 5.

If you re-declare variable in some other languages for example - result will be undefined, or NaN, but not in javascript.

3
  • Interesting. I get the same error when I try to redeclare a class. I had an Animal class with a generic speak function that looks like console.log(this.name + 'makes a sound.'). Of course after I declared it I realized 'make needed a space between the quote and the word. So I navigated up to the entry, fixed it accordingly and resubmitted thinking the new declaration would overwrite the previous. Clearly that isn't how javascript works though. So how should I deal with this? Jun 14, 2016 at 17:52
  • 2
    If you redeclare a variable using let or const, JavaScript throws an error. However, redeclaring variables using var does not throw an exception. The latter declarations merely shadow the previous declarations. Jul 28, 2018 at 7:37
  • I think it's also useful to point out that if you do var x=5; var x=x+10; alert(x); the result will be 15, i.e. in the second var, the original value of x assigned by the first var is accessible, and can be used in RHS expressions.
    – Doin
    Mar 22, 2020 at 11:22
48

An example of redeclaring a variable can be found in Google Analytics. When the JavaScript tracking code is initiated by the Google Analytics script, it declares or redeclares _gaq in this way:

var _gaq = _gaq || [];

In other words, if _gaq is already defined, _gaq is "redeclared" as itself. If it is not defined, it will be declared for the first time as an empty array.

This allows the Google Analytics tracking code to support other scripts which may need to use the variable before Google Analytics code has initiated. As @xralf pointed out, JavaScript allows for this.

Redeclaring a variable is useful in situations where it cannot be known if the variable has already been defined.

By redeclaring a variable conditionally, as Google Analytics tracking code does, it allows for a variable to safely originate from more than one place.

In this example it could be safe for other code using the _gaq variable to likewise check for a predefined _gaq variable. If it exists, it knows it can use it. If it doesn't exist, it knows that it should define it before trying to use it.

1
  • 1
    Very nice answer, +1, especially for the note about allowing a variable to "safely originate from more than one place". When you refactor JS chunks into separate files and want to be able to use bits and pieces as required it helps to be able to do exactly what you've mentioned in the _gaq example (horrible variable name, though, isn't it?). Oct 31, 2012 at 8:53
22

Why should I redeclare a variable?

You shouldn't. It makes for confusing code.

Is it practical in some situations?

No.

9
  • Your answer is very good, but I have to choose only one for accepting.
    – xralf
    Jul 31, 2011 at 9:22
  • It's more like accidentally or unknowingly redeclare a variable.
    – Adnan
    Aug 29, 2015 at 8:29
  • 2
    if I have two not nested loops in a single function, and the declared var i=0 is used only in the loop, where it was declared, why should I care to invent another name for the second loop? So this is at least one example, where the variable redeclaration is practical, I think
    – d.k
    Aug 3, 2016 at 7:31
  • 2
    I meant, that it is more convenient to work this way. You can manipulate (copy/paste etc.) lines of code with almost no caution (at least much less) about whether you should add/delete the declaration of the variable
    – d.k
    Aug 3, 2016 at 7:39
  • 1
    You probably shouldn't re-declare a variable in the same file, or within a function. But if you have multiple script files (in the context of a HTML page), then it's often the case that you'll need a variable to be (re-)declared in 2 or more of the files; cf. Steve Oliver's answer. So this is NOT a good answer.
    – Doin
    Mar 22, 2020 at 11:06
9

In javascript there is no block scope so it is advisable to redeclare a variable for clarification purposes; this makes for better code.

For example:

for (var x=0; x< 100; x++) { }

alert(x); //In most languages, x would be out of scope here.
          //In javascript, x is still in scope.


//redeclaring a variable helps with clarification: 
var x = "hello";
alert(x);
1
  • 2
    Now there are with let and const.
    – Manuel
    Dec 31, 2018 at 1:40
5

It doesn't lose it's value because of Hoisting

var x = 5;
var x;

// this is same as

var x; // undefined;
x = 5;

So when you say "If you redeclare a JavaScript variable, it will not lose its value."

As per hoisting, the declaration(s), all of them , move to the top. And then the variable is assigned.

var x = 25;
var x; // redeclare first time
var x; // redeclare second time

// is same as 

var x; // undefined
var x; // Not sure if this happens, but doesn't make a difference, it's still undefined
x = 25;

As for practicality, it happens sometimes. Look at @steveoliver 's answer.

3

Keep in mind that only variables declared with var can be re-declared. If you try to re-declare a variable declared with let or const (which is the ES2015 Javascript syntax that should be used in most cases nowadays), even worse than losing the value, an error will be thrown:

let foo = 'foo';
let foo;

So, in codebases which use modern Javascript syntax, re-declaring a variable simply isn't possible - the interpreter needs to be able to identify a single point in the code after which a let or const variable gets properly initialized. Before that point, the variable name will exist in the temporal dead zone.

1

In general, it can be considered bad style to have var assignments after other statements due to the problem of hoisting (see here). Using the "Single var pattern" (see here), redeclarations could only happen like in Steve Oliver's Google Analtyics example. I'd refactor the example above to:

var x, max = 100; // no further var declarations afterwards!

for (x = 0; x < max; x++) { }

alert(x);

// redeclaration 'var x = "hello"' doesn't make any sense here
// and would be complained about by JSLint/-Hint 
x = 'hello';
alert(x);

A redeclaration can make sense however when using default values for optional parameters (which is what the Google Analytics example is about, I assume):

function abc(param1) {
  var param1 = param1 || 'default value';
}
-1

It is pretty simple re-declaring doesn't actually affect anything, you just have to remember that if you reassign value within scope then the reassigned value is limited to scope and outside of scope it will still be globally declared value

var page =1 ;
function htmlcode(page) { 
page = "keka";
console.log("inside " + page);
}

htmlcode(page);
console.log("inside " + page);

Output : inside keka
         inside 1
1
  • 1
    You're wrong. The reason why in your case it didn't change the global variable "page" is simply because you made a function which has an argument with the same name.
    – peq42
    Jan 22, 2022 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.