'Remove previously selected geoJSON layer when selection changes

I have a Leaflet map with a select tag that, when a country is selected, the border is drawn around it. I can't seem to get it to remove the previous border when the selection changes though.

Here's my code so far:

//When country selected, show its border
  $("#countrySelector").change(function(){
    //Verify the function is picking up the iso_a3 value in the console
    var selectedCountry = $('#countrySelector').val();
    console.log("You have selected the country " + selectedCountry);

    //AJAX call to JSON data
    $.ajax({
      url: "countryBorders.php",
      dataType: "json",
      type: "POST",
      success: function(result) {
        var data = result["data"];

        //Create the polygon/border for the relevant country
        for(let i = 0; i < data.length; i++) {
          if(selectedCountry === result.data[i].properties.iso_a3) {
            var country = result.data[i];
            var countryStyle = {
              color: "green",
              weight: 0.7
            }
            let countryLayer;
            if(countryLayer) {
              map.removeLayer(countryLayer);
            }
            countryLayer = L.geoJSON(country, countryStyle).addTo(map);
          }
        }
      }
    })
  })

Am I doing something wrong towards the end?

I have seen other similar questions but can't seem to apply it to my example exactly.

Any help would be much appreciated.



Sources

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

Source: Stack Overflow

Solution Source