'Global map variable in Leaflet

I'm working in Leaflet, trying to do some zoom methods to remove layers when I zoom out.

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: '&copy; <a href="http://www.openstreetmap.org    /copyright">OpenStreetMap contributors</a>'
    //and add it to map

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

};

However, I am now trying to add some listener event that will remove layers when the map is zoomed.

map.on('zoomend', function () {
if (map.getZoom() > 4) {
    map.removeLayer(worldCountries);
}

});

$(document).ready(createMap);

I get an error saying "map is undefined." 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 createMap function so this seems to be the problem.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source