/    Sign up×
Community /Pin to ProfileBookmark

Global Variable Only If a Condition is Met

I wish to declare a global variable, but only if a certain condition is met. For example:

[CODE]
if (type1a == “voltage”)
{
voltage = document.f1.value1.value;
}
[/CODE]

except that now it is not global because it is contained within an if statement.

thanks

-ej-

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@tirnaAug 02.2010 — If you declare a variable within a function without the var keyword then the variable will be

global.

Assuming your IF block is in a function, then voltage will be global.

To test it, add

[CODE]
alert(voltage);
[/CODE]


somewhere outside the function and after it is called and if


[CODE]voltage = document.f1.value1.value;[/CODE] was executed you should see the value in the alert()
Copy linkTweet thisAlerts:
@Declan1991Aug 02.2010 — Either that, or declare voltage globally first (i.e. var voltage in global scope), or use window.voltage from anywhere (my preferred option). Furthermore, if statements don't form a closure, so if the if statement is in global scope (which it probably isn't but it'll illustrate the point), var voltage would create a global variable.
Copy linkTweet thisAlerts:
@Sterling_IsfineAug 02.2010 — I wish to declare a global variable, but only if a certain condition is met. For example:

[CODE]
if (type1a == "voltage")
{
voltage = document.f1.value1.value;
}
[/CODE]


except that now it is not global because it is contained within an if statement.
[/QUOTE]
It's still global, however conditional variable declaration can be a hazardous practice. Subsequently-written code branches may assume the variable's existence, and testing may not always expose the error.
×

Success!

Help @Icedfuse spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...