Global variables
In JavaScript—especially in modern JavaScript—variables are always declared with let
or const
(or, historically, var
):
function me() {
let name = "Charles"; // scoped to me
}
I’m not going to get into the details here, since there are thousands of other blog posts diving into the differences out there. Instead. I want to talk about declaring variables without these keywords:
function me() {
name = "Charles";
}
Up until the widespread adoption of ES Modules (and so long as you weren’t using strict mode) this was valid code. It declared name
as a global variable—on window
, if you’re in the browser.
Developers are usually warned against doing this, because the global scope in the browser is already pretty full of stuff and you can never be sure whether you’re going to step on something that already exists.
But I’m not just talking about browser APIs—did you know that every id
attribute maps to a value on window
(that is, the global namespace) in the browser?
<nav id="navbar">The nav goes here</nav>
<script type="text/javascript">
console.log(navbar) // => <nav id="navbar">
</script>
Thankfully we don’t tend to have to think about these things much nowadays—we’re well into the Age of ES Modules and if you’re not using "type": "module"
from the start then you’ve likely got some bundler or another that abstracts all of this out of your regular thinking. But there’s always value in understanding the platform.
Previous
An old story from YouTube, 10 years ago, about why the weight of the web page you're sending over the wire actually matters.