Like python is it possible to define global variable inside a function ?
for eg -
in python
def testFunc():
global testVar
testVar += 1
is there a way to define testvar global in javascript inside a function?
Like python is it possible to define global variable inside a function ?
for eg -
in python
def testFunc():
global testVar
testVar += 1
is there a way to define testvar global in javascript inside a function?
Simply ignore the var
keyword.
function testFunc() {
testVar = 1; // `testVar` is a Global variable now
}
Note: In the Python version of your code, you are not defining a global variable. You are referring the variable testVar
defined in the global scope.
Quoting from var
MDN Docs,
assigning a value to an undeclared variable implicitly declares it as a global variable (it is now a property of the global object)
You can assign it to the window-object:
function test() {
window.globalvariable = 'something';
}
Simply declare it outside of the function:
var testvar;
function test() {
testvar = 1;
//the rest of the code
}