In javascript, A variable is defined in a function. Then, how can it be used in all the code?

12/1/2019 7:00:29 AM

Swaroop Chandra

8 Answers

New Answer


You can not use a variable outside a function which is declared inside a function But if you declare it in global scope then you can use it in function as well as outside function


Declare that variable globally. Define it before the function Do like this var some; function addText(){ some = "hi" // use like this, don't declare it again } // You can call it anywhere in the code



A variable that is created within a function, can not be used or changed outside of the function. As far as the rest of the program is concerned, it doesnt know the variable even exists


If you want it to only exsist globaly as a udeclared variable, it should already do so if you are using the var keyword(it will only exsist on the stack). Otherwise, declare it globaly.


we can declare it out of the function or declare it globally.


Put the variables in a "Public class xxxx". Then call the variable from the class so it could be xxxx.x