Convert private variables into public variables

  • A+
Category:Languages

I'm trying to discover how to send some private variables to the global scope. I've created a brief demo:

function test() {     let private1 = 1, private2 = 2;      return private1; }  test(); // returns the first variable value, but not if I have multiple variables console.log(private1); // returns obvious error - how to make private variable global? 

Obviously logging any variables will return an error as they only exist in the local scope relative to the test function. So my question is, how can these variables be made public?

I've never had to use variables this way, nor could I find any other posts that explains this, so is this generally bad practice? I'm curious to know. Any explanation or guidance of how best to treat variables would be very helpful, thank you.

 


A variable declared inside a function is only available inside that said function, unless you declare it outside the function.

In this example, you can't use private1 outside the function.

function test() {   let private1 = 1;   return private1; } test(); console.log(private1);

You can't make it global otherwise from outside the scope of the said function.

In this example, you can use private1 outside the function.

let private1;  function test() {   private1 = 1;   return private1; } test(); console.log(private1);

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: