Search code examples
node.jsscopeglobal-variables

Is there anyway to change the value of global variable in function and access outside the local scope in js


Is there anyway to change the value of global variable in function and access the changed value of global variable outside the function in javascript or nodejs...

var x=8;
function changed(x)
{
   x=10;
 }
console.log(x);

The actual output is 8 but i want the value of x is 10. is it possible in javascript or nodejs


Solution

  • If you pass x then the parameter becomes local to the function, when a variable is global, you can just use it in any function to changes the value of the global variable, and it will reflect everywhere.

    var x=8;
    
    function changed() {
       x=10;
    }
    changed(x)
    console.log(x);