In scriptA I have this code:
var John = 'Doe';
and in scriptB:
alert(John);
But I don't want that the variables between the 2 scripts are shared, how can I hide the John variable for scriptB? Thanks in advance!
In scriptA I have this code:
var John = 'Doe';
and in scriptB:
alert(John);
But I don't want that the variables between the 2 scripts are shared, how can I hide the John variable for scriptB? Thanks in advance!
You can "hide" variables by putting them inside an IIFE (immediately invoked function expression) like this:
(function() {
// this variable is only accessible within this function block
var John = "Doe";
})();
// this causes an error because the variable John is not available outside the IIFE
alert(John);
This creates a private function scope which is immediately executed. This is a common design pattern for declaring variables which have local use, but you don't want broadly shared and you don't want to pollute or conflict with the global namespace.
You can use anonymous functions to hide variables:
<script>
(function(){
var John = 'Doe';
})();
</script>
A similar block can be repeated but variable can have different value in that block:
<script>
(function(){
var John = 'AnotherValue';
})();
</script>