Sunday 30 April 2017

javascript - 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 ?


Answer



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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...