Skip to content
Advertisement

Why is the variable `closed` being logged as `false`, if I define it globally as `0`?

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.

Advertisement

Answer

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>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement