In javascript, A variable is defined in a function. Then, how can it be used in all the code? | SoloLearn: Learn to code for FREE!

+10

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

+14

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

+11

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

+6

+3

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

+2

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.

+2

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

0

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

-1