2

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?

3 Answers 3

2

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)

Sign up to request clarification or add additional context in comments.

Comments

1

You can assign it to the window-object:

function test() {
    window.globalvariable = 'something';
}

Comments

1

Simply declare it outside of the function:

var testvar;

function test() {
    testvar = 1;
    //the rest of the code
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.