Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access outer function variables from inner function

Tags:

javascript

How to change value of x in function A() from function B()

function A() {
    var x = 10; // Value to be changed
    function B() {
        var x = 20;
        // From here i want to change the value of x (i.e. x=10 to x=40)
    }
    B();
}

A();
like image 560
Coolenough Avatar asked Dec 03 '22 02:12

Coolenough


2 Answers

Do not use var when intending to overwrite the variable. Using var creates a new variable, local to the scope in which it is declared. That's why x is not changing on the outside.

function A() {
    var x = 10;
    function B() {
        x = 20; // change x from 10 to 20
    }

    B(); // x is now changed
}
like image 89
David G Avatar answered Dec 25 '22 02:12

David G


If I understand your question, the following code is a solution:

function A() {
    var x = 10; // Value to be changed
    function B() {
        var x = 20;
        // From here i want to change the value of x (i.e. x=10 to x=40)
        changeX(40);
    }
    function changeX(y) {
        x = y;
    }
    B();
    alert(x);
}

A();

However there are more elegant approach, but it depends on your application.

like image 27
Luca Rainone Avatar answered Dec 25 '22 03:12

Luca Rainone