Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice declaring global variables in a.js file?

I have a .js file where I am initialising two parameters which are used in a seperate function :

var submyvar1;
var submyvar2;

function init(myvar1 , myvar2){
    submyvar1= myvar1;
    submyvar2= myvar2;
}

function (){
    //subvar1 & subvar 2 used here
}

Is declaring global variables like this a bad practice ?

If so, what is the alternative, wrap the entire .js file in an object ?

like image 245
blue-sky Avatar asked Feb 17 '23 17:02

blue-sky


1 Answers

At least it's not a good practice, you could use an immediated invoked function expression:

(function() {
    var x;
    var y;

    window.init = function(xValue, yValue) {
        x = xValue;
        y = yValue;
    }

    window.doWhateverYouWant = function() {
        console.log(x + y);
    }
}());

You could use this pattern unless you need access your global variable outside this .js file, when an cross-accessing between .js files or <script> elements are required, global variable is a simple solution (although you could use AMD or sth else instead).

like image 122
otakustay Avatar answered Feb 20 '23 08:02

otakustay