Jump to content

Lifetime of Variables


kwyjibear

Recommended Posts

W3Schools' JavaScript lessons state that a variable created in a function exists only inside that function. However I read elsewhere that that is not always the case. JavaScript tutorial at C PointAccording to them, a varialble declared in a function is local only if you use the var declaration. If you create the variable just by typing its name (example: variableName = "Hello World":) then it is considered global and will work outside the function.Is this so?

Link to comment
Share on other sites

I am not sure, but it is probably true, although it is not a good programming practice.You should always declare your variables and if you want them to be global declare them globally in the first place.

Link to comment
Share on other sites

Crazy, I had no idea. This runs fine in Firefox:

<script type="text/javascript">function test(){	test2 = "variable declared without var.";}test();document.write(test2 + "<br />");</script>

Link to comment
Share on other sites

Is this so?
Yeah that's right, var plays a big part.If you take jesh's example for instance, it will write out the text because var is not declaired, but if it was then nothing would be written.It's important that you know this, if you have a massive script and 2 functions have the same variable name within them and are not declaired with a var then this could mess up you results.
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...