Shadowing
Due to the fact that all scripts are dumped into the JavaScript
global scope, all variables, function, and objects are placed
in that scope. As scripts are loaded into the global scope they are loaded in the
order they are located as the HTML is parsed, because 3rd party libraries are
often used, and because scripts are written by humans, there is a high likelihood
that one or more of those scripts will contain one or more items that have
the same name.
If one script loads and is followed by another that has items with identical
identifiers (names), those that exist in the previous script will be shadowed
or overwritten by those found in the following script. This leads to hard to
identify and correct bugs that can waste a lot of development resources.
Script One
// This script is loaded first var varWithSameName = { name: 'Tim', say: function(){ return `This is the first variable with the name: ${this.name}`; } } console.log(varWithSameName.say());
// This script is loaded second // overrides (shadows) the variable with the same name in the first file var varWithSameName = { name: 'Freddy', say: function(){ return `This is the first variable with the name: ${this.name}`; } } console.log(varWithSameName.say());
Console Output
This is the first variable with the name: Tim This is the first variable with the name: Freddy
NOTE: only applicable when using 'var' to create variables.
When using 'let', JavaScript will throw an error that the variable name has
already been taken. This includes the case where one of the variables was created
using 'var' and the other was created using 'let', JS will still throw an error.
Script One
// using 'let' when declaring variables corrects this problem let willBreakIfShadowed = 'This will break if it is shadowed in another script.';
Script Two
// using 'let' when declaring variables corrects this problem var willBreakIfShadowed = 'Broken since script one has this variable and used let to define it.';
Console Output
Uncaught SyntaxError: Identifier 'willBreakIfShadowed' has already been declared at script-2.js:1
Published by