GoMega54 GoMega54 - 6 months ago 11
Javascript Question

How to make variables within a function available globally

How would I make the variables within the function available in the global scope without removing them from the function and so they are logged in the console?

function foo(){
var one = 1;
var two = 2;
}

foo();
console.log(one, two);

Answer

To access the variables outside of the function, you can declare them outside of it. The function will still have access to be able to assign to them.

var one, two;

function foo(){
  one = 1;
  two = 2; 
}

foo();
console.log(one, two);

Or, if you just need the values, you can have the function return them.

function foo(){
  var one = 1;
  var two = 2;
  return { one: one, two: two };
}

var result = foo();
console.log(result.one, result.two);

Comments