I am referencing multiple JS files within a single HTML file. I know that there should be no overlap of Variable and Function names in these JS files. However, is that limited to only Global Variables or all variables(even local variables within a function)?
1 Answer
// These will go into global scope
nonKeywordedVarA = true; // just don't
var nonKeywordedVarC = true;
function leaky () {
nonKeywordedVarB = true;
}
// These will stay where you put them
function nonLeakyA () {
var functionScoped = true;
}
function nonLeakyB () {
var functionScoped = false;
}
if (true) {
let blockScoped = true;
}
if (true) {
let blockScoped = false;
}
leaky();
nonLeakyA();
nonLeakyB();
// Here we log global scope
console.log(typeof nonKeywordedVarA)
console.log(typeof nonKeywordedVarB)
console.log(typeof nonKeywordedVarC)
console.log(typeof functionScoped)
console.log(typeof blockScoped)
It is limited only to variables in the same scope:
variables declared without
var,let,constkeywords (e.g. someVar = true). These go leak straight into global scope (egwindowobject)variables declared outside any function scope (or block scope in case of
let)
In short the answer to your question is don't worry about variables with the same name in different scopes.
1 Comment
Jagpreet Singh
My test environment is currently down due to maintenance. Will test this and respond as soon as possible. Thank you so much for your reply!
(function () { 'use strict'; /* script */ })();then you cannot leak anything to the global scope accidentally. Only explicitly set properties on thewindowobject will be globalstrictas things do get pretty strict and confusing sometimes :)delete Object.prototypeetc.