Global map variable in Leaflet
<p>I'm working in Leaflet, trying to do some zoom methods to remove layers when I zoom out.</p>
<pre><code>var map;

//function to instantiate the Leaflet map
function createMap(){
//create the map
map = L.map('map', {
    //set geographic center
    center: [41.4, -110],
    //set initial zoom level
    zoom: 4,
    maxZoom: 8,
    minZoom: 2
});


//add OSM base tilelayer
L.tileLayer('http://{s}.basemaps.cartocdn.com/dark_all/{z}/{x}/{y}.png', {
    //set attribute info (source)
    attribution: '&amp;copy; &lt;a href=&quot;http://www.openstreetmap.org    /copyright&quot;&gt;OpenStreetMap contributors&lt;/a&gt;'
    //and add it to map

}).addTo(map);
 L.geoJson(worldCountries).addTo(map);

};
</code></pre>
<p>However, I am now trying to add some listener event that will remove layers when the map is zoomed.</p>
<pre><code>map.on('zoomend', function () {
if (map.getZoom() &gt; 4) {
    map.removeLayer(worldCountries);
}

});

$(document).ready(createMap);
</code></pre>
<p>I get an error saying &quot;map is undefined.&quot; I thought I declared it globally at the very beginning of the script? Indeed, I can't seem to access the map variable outside of the <code>createMap</code> function so this seems to be the problem.</p>