Convert Private Variables Into Public Variables
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.
Answer
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);
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM