Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a Javascript variable twice in same scope - Is it an issue?

Would the following code cause any issues?:

var a = 1; var a = 2; 

My understanding is that javascript variables are declared at the start of the scope. For example:

var foo = 'a'; foo = 'b'; var bar = 'c'; 

Is processed as:

var foo; var bar; foo = 'a'; foo = 'b'; bar = 'c'; 

Therefore would my initial code snippet become:

var a; a = 1; a = 2; 

Or would it become:

var a; var a; a = 1; a = 2; 

I understand that declaring a javascript variable twice in the same scope isn't good practice, but I'm more interested in the impact of doing this.

like image 549
Curtis Avatar asked Feb 12 '14 11:02

Curtis


People also ask

Can I declare a variable two times in JavaScript?

It is okay to declare variables with same name in different functions. Show activity on this post. Variables declared inside a function only exist in the scope of that function, so having the same variable name across different functions will not break anything.

Can you declare the same variable twice?

Both var and let can be used to declare local variables within a function. But, let does not allow for re-declaration of the same variable within the same block.

How many times can you declare a variable?

a variable/function can be declared any number of times but it can be defined only once.

What happens if you declare a variable with the same name in two or more place?

You'll have the same result as though you didn't have it, meaning foo will be overwritten with the new value.


1 Answers

As you said, by twice of more the same var, JavaScript moves that declaration to the top of the scope and then your code would become like this:

var a; a = 1; a = 2; 

Therefore, it doesn't give us any error.

This same behaviour occurs to for loops (they doesn't have a local scope in their headers), so the code below is really common:

for (var i = 0; i < n; i++) {     // ... } for (var i = 0; i < m; i++) {     // ... } 

That's why JavaScript gurus like Douglas Crockford suggest programmers to manually move those declarations to the top of the scope:

var i;    // declare here for (i = 0; i < n; i++) {    // initialize here...     // ... } for (i = 0; i < m; i++) {    // ... and here     // ... } 
like image 121
Danilo Valente Avatar answered Oct 14 '22 10:10

Danilo Valente