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 ofvar
asclosed
is a global variable used by JavaScript runtime so to make it local to the scope of the code you can uselet
instead ofvar
which set the variable to global scope considering the globalclosed
property.closed
refers towindow.closed
; it’s always a boolean, and redefining it produces a linter warning like “Redefinition ofclosed
”.Variables that behave like this can be found in these lists:
WindowOrWorkerGlobalScope
propertiesWindow
propertiesWorkerGlobalScope
propertiesRun the snippet to get a full list of variable names that you can’t safely use in the global scope:
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
, andparent
. Furthermore, regarding the change of action on assignment upon setters, something likevar location = "Podunk, USA";
actually redirects you to the location./Podunk, USA
.There’s a related issue of using function names like
lang
,checked
,autocomplete
oranimate
in event attributes likeonclick
.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:
Using
let
instead ofvar
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";
: