kwyjibear Posted October 20, 2006 Share Posted October 20, 2006 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 More sharing options...
aspnetguy Posted October 20, 2006 Share Posted October 20, 2006 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 More sharing options...
jesh Posted October 20, 2006 Share Posted October 20, 2006 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 More sharing options...
scott100 Posted October 20, 2006 Share Posted October 20, 2006 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 More sharing options...
Recommended Posts
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 accountSign in
Already have an account? Sign in here.
Sign In Now