bb1769

Tip:  Don't use "map" for HTML div and JavaScript variable

Discussion created by bb1769 on Jan 16, 2015
Latest reply on Jan 16, 2015 by csergent08

Tip for developers: avoid the pattern used in the JavaScript API samples that use "map" for the map HTML div and JavaScript variable. So instead of this:

 

<script>

  var map;

  require(["esri/map", "dojo/domReady!"], function(Map) {

  map = new Map("map", {

   basemap: "topo",

   center: [-122.45, 37.75], // longitude, latitude

   zoom: 13

  });

  });

</script>

</head>

<body>

<div id="map"></div>

</body>

 

Do something like this instead:

 

<script>

  var mapObj;

  require(["esri/map", "dojo/domReady!"], function(Map) {

  mapObj = new Map("mapDiv", {

   basemap: "topo",

   center: [-122.45, 37.75], // longitude, latitude

   zoom: 13

  });

  });

</script>

</head>

<body>

<div id="mapDiv"></div>

</body>

 

Why? The JavaScript engine (at least some of them) will use a div instead of a JS variable if a variable of that name doesn't exist. This can lead to confusing errors. If you later change the name of the map object, but use "map" as the JS map object, JavaScript will instead substitute the HTML div as the object used. That div is not the same thing as the map object! You will likely then get an odd error sometime later when the code tries to use that div as if it were the map object, since it has none of the same methods and properties. I ran into that problem as discussed in this forum post: https://community.esri.com/message/450315

 

This extends generally to all IDs and JavaScript variables - don't overlap names. These days most applications create a few custom objects and store objects within those few, which is a good practice for avoiding this kind of problem.

 

I would like to see ESRI modify the JS API samples to remove these name overlaps, since developers tend to use code as-is from samples.

Outcomes