...

View Full Version : Declare variables question



Krupski
12-13-2011, 07:09 PM
THIS IS NOT HOMEWORK

Hi all,

Simple question: Is it "legal" to conditionally declare variables?

For example:

First


if (name) {
var age = 54;
var year = 1957;
}

Second


var age;
var year;
if (name) {
age = 54;
year = 1957;
}
Is "First" wrong and "Second" right? Or are they both equally OK?

Thanks.

-- Roger


Please explain your answer.

rnd me
12-13-2011, 07:34 PM
the second is arguably easier to maintain among a group of coders, but both work fine as far as javascript is concerned.

thesam101
12-14-2011, 04:32 PM
Javascript isn't 'block scope' meaning any variable declared inside blocks (such as if) can be accessed outside, and vice versa.

So in short, no, in javascript, it makes no difference whatsoever. :D

Generally though, a lot of people consider it best practice to declare them outside the block (like in second example), purely becuase this help reduce confusing for coders moving from block scoped languages, like C, C#, C++ etc. ;)

Dormilich
12-14-2011, 05:29 PM
though there is an issue with the first one. if the condition is not executed then on the next call to the variable it is instantiated as global variable, which might interfere with other parts of your script. the second version makes sure the variables are local regardless of the condition.

thesam101
12-14-2011, 05:40 PM
though there is an issue with the first one. if the condition is not executed then on the next call to the variable it is instantiated as global variable, which might interfere with other parts of your script. the second version makes sure the variables are local regardless of the condition.

Very true.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum