A very simple question I'd like to ask, why intializing a var outside a function, it cannot be used in that function?


<script type="text/javascript" >

var myvariable = document.getElementById("someID");

   function someMethod(){
        //some stuff here, and I cannot use myvariable inside here why?



Recommended Answers

All 5 Replies

In some programming language , it is called a modular level variable, the reason for doing this is to make the variable accessible for the entire module or page(for web development). Of course it is possible to access the variable inside the function. Maybe there's an error inside the function

Member Avatar

Show how you're trying to use the variable in the function.

place that script code file before the end of </body> tag

i think it may work

pls check it once and let me know the status

happy coding

In JS you can, like in C.
But it's a bad practice messing with the global directly under the local scope of a function, although on some instances it's ok. But as much as possible try to hesitate from doing so; you have to seperate concerns and responsibility. In a large project or framework, if you happend to directly alter or use a global variable, you might end up screwing with other programmers in your team. They might end up debugging he code for a day, just to find out a function or a method had been referencing on a global var. Sweet, isn't it. But S&%# it happens. T_T

Anyway, you can declare a local variable by redeclaring the same variable in the function, in this way, it won't clutter the global space, or use the global variable.

Additionally, if you are having problem accessing the myvariable in your function, it would be appropriate to post in the whole definition of the function itself. As what I said earlier, you should be able to access that variable inside your function; judgin from the code you posted.

Sorry for not replying sooner!

You guys are correct, Global variables are not recommended especially in JS. I've submitted my project and I used one global variabale and my instructor commented on this.

However, the problem was using a global var in a javascript function but appearently it was impossible to use. I really forgot what was the problem I faced due to so many lines I wrote.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.