I know this must be really basic stuff but I don’t understand how the scope is working. I want the closed
variable be known in the entire JavaScript file.
I have something like that (in jQuery):
var closed = 0;
$(function(){
console.log(closed);
});
But closed
is getting logged as false
. I tried many things with load
and onload
functions, but I failed.
Use let
instead of var
as closed
is a global variable used by JavaScript runtime so to make it local to the scope of the code you can use let
instead of var
which set the variable to global scope considering the global closed
property.
let closed=0;
$( function() {
console.log(closed);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
closed
refers to window.closed
; it’s always a boolean, and redefining it produces a linter warning like “Redefinition of closed
”.
This read-only property indicates whether the referenced window is closed or not.
Variables that behave like this can be found in these lists:
WindowOrWorkerGlobalScope
properties
Window
properties
WorkerGlobalScope
properties
Run the snippet to get a full list of variable names that you can’t safely use in the global scope:
const props = Object.entries(Object.getOwnPropertyDescriptors(window)),
undesirable = {
set: (desc) => desc,
configurable: (desc) => !desc,
writable: (desc) => !desc
};
Array.from(document.querySelectorAll("[id]"))
.forEach((span) => span.innerHTML = props
.filter(([prop, {[span.id]: desc}]) => undesirable[span.id](desc))
.map(([prop]) => `<code>${prop}</code>`)
.join(", "))
code{
background: #eee;
padding: 1px 3px;
}
<p>Properties that have a Setter which may change the type or the action, when a value is set to it:</p>
<span id="set"></span>
<hr/>
<p>Properties that are not configurable (no type change allowed):</p>
<span id="configurable"></span>
<hr/>
<p>Properties that are read-only:</p>
<span id="writable"></span>
You’ll notice, it’s a lot. It’s also a lot of short, common variable names like name
, length
[1], [2], status
[1], [2], self
, top
, menubar
, and parent
. Furthermore, regarding the change of action on assignment upon setters, something like var location = "Podunk, USA";
actually redirects you to the location ./Podunk, USA
.
There’s a related issue of using function names like lang
, checked
, autocomplete
or animate
in event attributes like onclick
.
Moral of the story: avoid global variables like these. They’ll just clash with other global properties. Always use scoped variables, such as in IIFEs:
(function(){
var closed = 0;
$(function(){
console.log(closed);
});
})();
Using let
instead of var
is another solution.
Since I don’t use jQuery for most of my code, I prefer to wrap everything in a DOMContentLoaded
listener where I can scope all the variables I need, and, in addition, use "use strict";
:
// My personal boiler-plate:
addEventListener("DOMContentLoaded", function(){ "use strict";
// Code goes here.
});