How do you access a variable inside a function without placing the variable inside of the function in Javascript ?

Recommended Answers

if you declare variable outside a function (before declare function) then you can access and change it inside eg

var someVariable;
function someFunction(){
    someVariable = 5;
}

alert(someVariable); // undefined
someFunction();
alert(someVariable); // 5

but if you redeclare variable with same name inside a function then it's …

Jump to Post

All 3 Replies

I think I need to place a parameter inside the function ?

if you declare variable outside a function (before declare function) then you can access and change it inside eg

var someVariable;
function someFunction(){
    someVariable = 5;
}

alert(someVariable); // undefined
someFunction();
alert(someVariable); // 5

but if you redeclare variable with same name inside a function then it's a local variable and you lost access to global variable inside a function

var someVariable;
function someFunction(){
    var someVariable = 5;
}

alert(someVariable); // undefined
someFunction();
alert(someVariable); // undefined

Then declaring a variable which holds data outside a function, if I call that variable as a parameter inside the function it should be treated as though the variable is inside the function ?

If so that isn't working.

Be a part of the DaniWeb community

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