How to test if a layer exist in a MapBox GL JS map?

Better way:

var mapLayer = map.getLayer('route');

    if(typeof mapLayer !== 'undefined') {
      // Remove map layer & source.
      map.removeLayer('route').removeSource('route');
    }

From: https://github.com/mapbox/mapbox-gl-js/issues/4466#issuecomment-288177042

To safely remove a layer that may or may not exist, guard the call to removeLayer with getLayer:

if (map.getSource("route")) {
    map.removeSource("route");
}

if (map.getLayer("route")) {
    map.removeLayer("route");
}

I've solved in this manner, probably not the best solution but it's working

    try {
      map.removeSource("route");
      map.removeLayer("route");
    }
    catch(err) {
//        alert("Error!");
    }