nim007
nim007

Reputation: 3058

Any way to access local scope variable in outer scope in Javascript?

Is there any way to make local scope variable accessible in outer scope without creating an object or without using 'this'?

Say,

function foo(){
  var bar = 10;

}

Any way to make variable 'bar' available outside function 'foo' scope?

Upvotes: 3

Views: 2818

Answers (5)

obed
obed

Reputation: 1

function myFunction() { myVar = 'Hello'; // global variable } myFunction(); console.log(myVar); // output: "Hello"

Upvotes: 0

Abdul Rahman Mohsen
Abdul Rahman Mohsen

Reputation: 115

You can do something like this:

var myScopedVariables = function foo(){
    var bar = 10;
    return [bar];
} 
console.log(myScopedVariables);

Upvotes: 1

Avinash T.
Avinash T.

Reputation: 2349

You can't access local variable outside the function.

Following post might help you to understand scopes in more detail -

What is the scope of variables in JavaScript?

Upvotes: 2

jonny
jonny

Reputation: 3098

Assign the value to a property of the window object:

function foo(){
    window.bar = 10;
}

console.log(window.bar); //10

EDIT:

Since you can't accept his answer, then no - what you're asking for is impossible. Only solution is to declare the variable in the global scope, then initialize it later.

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 122026

No. Simply you can't. Scope is scope. If you want to access outside, make it declare outside and use it.

That's how things designed. I don't suggest any crappy way to make it possible.

Upvotes: 7

Related Questions