Module 01 - The JavaScript You Actually Need
Level 0 ยท Foundations ยท ๐ข Beginner ยท 4 hours ยท Prereq: Module 00
What you'll build
A small "spatial toolkit" of pure JavaScript functions - distance, bounding box, grouping, filtering, async fetching - written in exactly the style the ArcGIS SDK expects. Every pattern here reappears in Level 2 onward, so you are building your own reference file.
File: spatial-toolkit.js. Keep it. You will import from it later.
Why this matters
The ArcGIS SDK is not a beginner-friendly library that hides JavaScript from you. It is a large, object-oriented, promise-heavy API that assumes you are fluent. Almost every "the SDK is confusing" complaint is actually one of five JavaScript gaps:
- Not understanding that
awaitis doing something to control flow - Not understanding object references vs copies
- Not understanding
thisin callbacks - Not understanding modules and why imports have paths
- Not understanding that array methods return new arrays
This module closes all five. If you are already fluent, skim the SDK-specific callouts and do the exercises - those are not generic JS practice.
Concepts
1. Modules - why every SDK import has a path
The SDK ships as ES modules. One class per file.
import Map from "@arcgis/core/Map.js";
import MapView from "@arcgis/core/views/MapView.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";
Read that as: "from the package @arcgis/core, the file at views/MapView.js, take the
default export."
Three import forms you will see:
import Map from "@arcgis/core/Map.js"; // default export - a class
import * as reactiveUtils from "@arcgis/core/core/reactiveUtils.js"; // namespace - a module of functions
import { watch, when } from "@arcgis/core/core/reactiveUtils.js"; // named exports
Changed in 5.0 - deep paths end in
.js. In older 4.x code you'll seefrom "@arcgis/core/Map"without the extension. Both often work through bundler resolution, but.jsis correct and required for strict ESM.
Why one class per file matters: it is what lets your bundler drop the 95% of the SDK you
don't use. If the SDK exported everything from one index, your Legend-only app would ship
the routing engine. Module 40 measures this.
Dynamic import - deferring a chunk
const { default: Graphic } = await import("@arcgis/core/Graphic.js");
This loads the module when the line runs, not at page load. The production code in this
repository uses this heavily so that the marketing homepage doesn't download the 3D engine.
You'll see the pattern in src/components/viewer/Sidebar/tools/.
Note the destructuring: a dynamic import resolves to the module namespace object, so the
default export is at .default.
2. const, let, and what "immutable" doesn't mean
const view = new MapView({ container: "viewDiv" });
view.zoom = 12; // โ
fine - mutating the object
view = otherView; // โ TypeError - rebinding the name
const prevents reassigning the name. It says nothing about the object's contents.
This trips people up constantly with SDK objects, which you mutate all the time.
Rule for this course: const by default. let only when you genuinely reassign.
Never var.
3. Objects are references
const symbol = { type: "simple-marker", color: "red", size: 8 };
const bigSymbol = symbol;
bigSymbol.size = 20;
console.log(symbol.size); // 20 โ you changed both
There is one object and two names for it. To actually copy:
const bigSymbol = { ...symbol, size: 20 }; // shallow copy with an override
SDK-specific: this bites hardest with renderers.
// โ Mutating the live renderer - the view may not notice, and you've lost the original
layer.renderer.symbol.color = "blue";
// โ
Clone, change, reassign - this triggers a redraw
const renderer = layer.renderer.clone();
renderer.symbol.color = "blue";
layer.renderer = renderer;
SDK objects (anything extending Accessor) have a .clone() method. Use it. The SDK watches
for property assignment, not deep mutation, so in-place edits often just don't render.
4. Destructuring
Pull values out of objects and arrays by shape.
const { latitude, longitude } = point; // object
const { spatialReference: sr } = geometry; // rename
const { wkid = 4326 } = spatialReference; // default if undefined
const [x, y, z] = coordinatesArray; // array
const { attributes: { NAME, POPULATION } } = graphic; // nested
You will see this constantly in SDK code:
view.on("click", async (event) => {
const { results } = await view.hitTest(event);
const [first] = results;
if (!first) return;
const { graphic } = first;
console.log(graphic.attributes);
});
Default values only apply to undefined, not null. const { a = 1 } = { a: null }
gives you null. Feature service attributes are frequently null, so this matters:
// โ Doesn't do what you want when HEIGHT is null in the database
const { HEIGHT = 10 } = graphic.attributes;
// โ
const height = graphic.attributes.HEIGHT ?? 10;
5. ??, ?. and ||
const height = attrs.HEIGHT ?? 10; // 10 only if null/undefined
const height = attrs.HEIGHT || 10; // 10 if null, undefined, 0, "", false โ bug for 0!
const name = layer?.portalItem?.title; // undefined instead of throwing
layer?.refresh?.(); // call only if it exists
|| vs ?? is a real bug source in GIS. Elevations, counts, and measurements are
legitimately 0. elevation || 100 silently turns sea level into 100 m.
6. Array methods
The four you will use every day:
const cities = [
{ name: "Kingston", pop: 132000, province: "ON" },
{ name: "Halifax", pop: 439000, province: "NS" },
{ name: "Guelph", pop: 143000, province: "ON" },
];
cities.filter(c => c.pop > 140000); // โ subset (new array)
cities.map(c => c.name); // โ transformed (new array)
cities.find(c => c.name === "Guelph"); // โ one item or undefined
cities.reduce((sum, c) => sum + c.pop, 0); // โ single value: 714000
All of them return a new value and leave the source alone. sort() and reverse() are
the exceptions - they mutate. cities.slice().sort(...) if you care.
Grouping - no built-in until Object.groupBy (very recent); do it with reduce:
const byProvince = cities.reduce((acc, c) => {
(acc[c.province] ??= []).push(c);
return acc;
}, {});
// { ON: [Kingston, Guelph], NS: [Halifax] }
You will write this exact function for feature attributes at least three times in this course.
SDK-specific: query results give you featureSet.features, an array of Graphics.
The attributes are one level down:
const { features } = await layer.queryFeatures(query);
const names = features.map(f => f.attributes.NAME);
const total = features.reduce((s, f) => s + (f.attributes.POPULATION ?? 0), 0);
7. Promises and async/await - the big one
Almost everything in the SDK that touches a network or waits for rendering returns a Promise.
layer.load() // Promise<Layer>
view.when() // Promise<View>
view.whenLayerView(layer) // Promise<LayerView>
layer.queryFeatures(query) // Promise<FeatureSet>
view.goTo(target) // Promise<void>
view.hitTest(event) // Promise<HitTestResult>
bufferOperator.load() // Promise<void>
A Promise is a box that will eventually contain a value or an error.
// Three ways to open the box:
// 1. .then / .catch - chaining
layer.queryFeatures(q)
.then(fs => console.log(fs.features.length))
.catch(err => console.error(err));
// 2. async/await - sequential-looking
async function count() {
try {
const fs = await layer.queryFeatures(q);
console.log(fs.features.length);
} catch (err) {
console.error(err);
}
}
// 3. Promise.all - parallel
const [a, b, c] = await Promise.all([
layerA.queryFeatures(q),
layerB.queryFeatures(q),
layerC.queryFeatures(q),
]);
What await actually does: it pauses the async function, immediately returns a pending
Promise to whoever called it, and resumes when the awaited Promise settles. It does not block
the browser. Everything else keeps running.
The mistake everyone makes - sequential when you meant parallel:
// โ 3 round trips, one after another. 900 ms.
const a = await layerA.queryFeatures(q);
const b = await layerB.queryFeatures(q);
const c = await layerC.queryFeatures(q);
// โ
3 round trips at once. 300 ms.
const [a, b, c] = await Promise.all([
layerA.queryFeatures(q), layerB.queryFeatures(q), layerC.queryFeatures(q),
]);
Use sequential only when B genuinely needs A's result.
Promise.allSettled when one failure shouldn't kill the batch:
const results = await Promise.allSettled(layers.map(l => l.load()));
const loaded = results.filter(r => r.status === "fulfilled").map(r => r.value);
const broken = results.filter(r => r.status === "rejected");
This is the right call for "load all the layers in this WebMap" - one dead service should not blank the map.
8. The load lifecycle - the thing that confuses everyone
const layer = new FeatureLayer({ url: "https://.../FeatureServer/0" });
console.log(layer.fields); // null - nothing has been fetched yet
console.log(layer.geometryType); // null
console.log(layer.title); // null
await layer.load(); // โ now the service metadata request happens
console.log(layer.fields); // [ Field, Field, ... ]
console.log(layer.geometryType); // "point"
console.log(layer.title); // "USA Major Cities"
The constructor is cheap and synchronous. Nothing is fetched until something loads it. Adding the layer to a map loads it implicitly, which is why it "sometimes works" - a race you should not rely on.
Timeline diagram - memorise this:
new FeatureLayer() โ object exists, metadata null
โโ await layer.load() โ fields, geometryType, extent, capabilities populated
new MapView({map}) โ view exists, not drawing yet
โโ await view.when() โ view ready: extent, ui, spatialReference valid
โโ await view.whenLayerView(layer) โ LayerView ready:
filter / effect / highlight / client query
9. Classes, this, and arrow functions
The SDK is class-based. You mostly construct, rarely extend.
const layer = new FeatureLayer({ url, outFields: ["*"], popupTemplate });
That object literal is the constructor's properties argument, and it maps one-to-one to the class's writable properties. This is why the API reference's property list doubles as the constructor documentation.
this in callbacks - use arrow functions and stop thinking about it:
class MapController {
constructor(view) {
this.view = view;
// โ `this` is the event target, not the controller
// view.on("click", function (e) { console.log(this.view); });
// โ
arrow functions capture `this` lexically
view.on("click", (e) => console.log(this.view.zoom));
}
}
Rule for this course: always use arrow functions for callbacks. There is no case in the
SDK where you want the dynamic this.
10. Cleanup - handles
Every subscription in the SDK returns a handle with a .remove().
const handle = view.on("click", onClick);
// later
handle.remove();
If you don't remove it, the closure stays alive, and everything it references stays alive with it - including the view, the layers and their downloaded features. This is the #1 memory leak in SDK applications and it has its own module (18) and its own React module (37).
Convention that scales:
const handles = [];
handles.push(view.on("click", onClick));
handles.push(reactiveUtils.watch(() => view.zoom, onZoom));
// teardown
handles.forEach(h => h.remove());
handles.length = 0;
11. fetch, JSON, and errors
async function loadEarthquakes() {
const res = await fetch(
"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
);
if (!res.ok) throw new Error(`HTTP ${res.status} ${res.statusText}`);
return res.json();
}
fetch does not reject on 404 or 500. It only rejects on network failure. You must check
res.ok yourself. Forgetting this produces "cannot read property of undefined" three functions
away from the real problem.
Aborting a request that's no longer needed (matters when the user pans fast):
const controller = new AbortController();
const res = await fetch(url, { signal: controller.signal });
// somewhere else
controller.abort();
The SDK accepts an abort signal too: layer.queryFeatures(query, { signal }).
Build it - the spatial toolkit
Create spatial-toolkit.js. Type each function, run it, then read the explanation.
Step 1 - Distance between two lon/lat points
// spatial-toolkit.js
const EARTH_RADIUS_M = 6_371_008.8; // IUGG mean radius
const toRadians = (degrees) => (degrees * Math.PI) / 180;
/**
* Great-circle distance between two WGS84 points, in metres.
* @param {[number, number]} a - [longitude, latitude]
* @param {[number, number]} b - [longitude, latitude]
*/
export function haversineDistance([lon1, lat1], [lon2, lat2]) {
const dLat = toRadians(lat2 - lat1);
const dLon = toRadians(lon2 - lon1);
const ฯ1 = toRadians(lat1);
const ฯ2 = toRadians(lat2);
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(ฯ1) * Math.cos(ฯ2) * Math.sin(dLon / 2) ** 2;
return 2 * EARTH_RADIUS_M * Math.asin(Math.sqrt(h));
}
What this does: computes distance across the curved Earth. Note the parameter
destructuring - [lon, lat], which is the order GeoJSON and the ArcGIS SDK both use.
Why you're writing it by hand when the SDK has geodeticDistanceOperator: because in
Module 25 you need to recognise when the SDK's answer is wrong for your CRS, and you can only
do that if you know what the right answer looks like.
Test it:
// Kingston ON โ Toronto ON, roughly 240 km
console.log(haversineDistance([-76.481, 44.231], [-79.383, 43.653]));
// โ 242000
Step 2 - Bounding box from a set of points
/**
* Axis-aligned bounding box of an array of [lon, lat] pairs.
* @returns {{xmin:number, ymin:number, xmax:number, ymax:number}}
*/
export function boundingBox(points) {
if (!points?.length) return null;
return points.reduce(
(box, [x, y]) => ({
xmin: Math.min(box.xmin, x),
ymin: Math.min(box.ymin, y),
xmax: Math.max(box.xmax, x),
ymax: Math.max(box.ymax, y),
}),
{ xmin: Infinity, ymin: Infinity, xmax: -Infinity, ymax: -Infinity }
);
}
What this does: one pass, reduce with an accumulator seeded at infinities so the first
point always wins both comparisons.
Where you'll use it: computing an extent to view.goTo() when your data has no server-side
extent - for example a client-side GraphicsLayer.
Step 3 - Group features by an attribute
/**
* Group an array of objects by the value of a key selector.
* @param {Array} items
* @param {(item:any) => string} keyOf
* @returns {Record<string, Array>}
*/
export function groupBy(items, keyOf) {
return items.reduce((acc, item) => {
const key = keyOf(item);
(acc[key] ??= []).push(item);
return acc;
}, {});
}
What (acc[key] ??= []).push(item) does: if acc[key] is null/undefined, assign [] to it;
either way, evaluate to the array and push. It replaces a three-line if.
Usage with SDK features:
const byType = groupBy(features, f => f.attributes.LAND_USE ?? "UNKNOWN");
Step 4 - Summary statistics
/**
* min / max / sum / mean / count for a numeric field, ignoring null and NaN.
*/
export function summarise(items, valueOf) {
const values = items
.map(valueOf)
.filter((v) => typeof v === "number" && Number.isFinite(v));
if (!values.length) {
return { count: 0, min: null, max: null, sum: 0, mean: null };
}
const sum = values.reduce((a, b) => a + b, 0);
return {
count: values.length,
min: Math.min(...values),
max: Math.max(...values),
sum,
mean: sum / values.length,
};
}
Why the Number.isFinite filter: feature service numeric fields are null when unpopulated,
and Math.min(...[1, null, 3]) returns 0 because null coerces to 0. That silent wrong
answer is the kind of thing that ships.
Math.min(...values)warning: spreading blows the argument limit at roughly 100k elements. For big arrays use a reduce. Noted here because feature queries return big arrays.
Step 5 - Fetch with real error handling
/**
* Fetch JSON with status checking and optional abort.
*/
export async function fetchJson(url, { signal, timeoutMs = 15000 } = {}) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
// Chain the caller's signal to ours so either can cancel
signal?.addEventListener("abort", () => controller.abort(), { once: true });
try {
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) {
throw new Error(`Request failed: ${res.status} ${res.statusText} - ${url}`);
}
return await res.json();
} finally {
clearTimeout(timer);
}
}
What the finally is for: clearing the timeout whether the request succeeded, failed, or
was aborted. Without it you leak a timer per request.
Why { once: true }: the listener removes itself after firing, so chained aborts don't
accumulate.
Step 6 - Debounce (you will need this in Module 18)
/**
* Returns a debounced version of fn that only runs after `wait` ms of quiet.
* Also exposes .cancel().
*/
export function debounce(fn, wait = 250) {
let timer = null;
const debounced = (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
debounced.cancel = () => clearTimeout(timer);
return debounced;
}
Where this matters: view.watch("extent", ...) fires on every animation frame during a pan.
Querying a service on every frame will get you rate-limited. Debounce to 300 ms and the app
becomes usable.
Step 7 - Try the whole toolkit
// test.js
import { haversineDistance, boundingBox, groupBy, summarise, fetchJson } from "./spatial-toolkit.js";
const data = await fetchJson(
"https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"
);
// GeoJSON: features[].geometry.coordinates = [lon, lat, depth_km]
const quakes = data.features.map((f) => ({
place: f.properties.place,
magnitude: f.properties.mag,
depthKm: f.geometry.coordinates[2],
coords: [f.geometry.coordinates[0], f.geometry.coordinates[1]],
}));
console.log("count:", quakes.length);
console.log("magnitude stats:", summarise(quakes, (q) => q.magnitude));
console.log("bbox:", boundingBox(quakes.map((q) => q.coords)));
const bands = groupBy(quakes, (q) =>
q.magnitude >= 6 ? "major" : q.magnitude >= 4.5 ? "moderate" : "minor"
);
console.log("bands:", Object.entries(bands).map(([k, v]) => `${k}: ${v.length}`));
// Nearest quake to Tokyo
const tokyo = [139.6917, 35.6895];
const nearest = quakes
.map((q) => ({ ...q, distanceKm: haversineDistance(tokyo, q.coords) / 1000 }))
.sort((a, b) => a.distanceKm - b.distanceKm)[0];
console.log("nearest to Tokyo:", nearest.place, Math.round(nearest.distanceKm), "km");
Run it with node test.js (Node 20+ has fetch built in) or paste into a browser console
inside a module script.
You have just done the entire data pipeline of a web GIS app - fetch, parse, transform, group, aggregate, sort - without any map library at all. Everything in Level 2 onward is this plus rendering.
How it works
Why the SDK returns Promises instead of taking callbacks
Two reasons. First, composition: Promise.all and await compose; nested callbacks do not.
Second, and more importantly for the SDK - a Promise can be awaited after it has already
resolved, and it will resolve again immediately.
await view.when(); // waits
await view.when(); // returns instantly, view is already ready
That property is what makes view.when() safe to call from anywhere in your code without
tracking whether the view is ready yet. A callback API would need you to check first.
Why ??= and ?. exist in a GIS context specifically
Spatial data is sparse by nature. A parcels layer has a BUILD_YEAR that is null for vacant
lots. A points layer has Z only where a survey measured it. A joined table has nulls where
the join missed.
Optional chaining and nullish coalescing let you write the tolerant code the data demands
without an if pyramid. Get comfortable with them now.
Closures - why your event handler sees stale data
let count = 0;
view.on("click", () => console.log(count)); // captures the *variable*, not the value
count = 5;
// click โ logs 5 โ
That works because let count is one binding. But in React (Module 37):
const [count, setCount] = useState(0);
useEffect(() => {
view.on("click", () => console.log(count)); // captures THIS RENDER's count - 0, forever
}, []);
Each render creates a new count constant. The handler registered in the first effect run
closed over the first one. This is the "stale closure" problem, and the SDK makes it common
because handlers are long-lived. The fix - mirroring state into refs - is exactly what this
repo does in DesignToolbar.jsx with editHeightRef, activeToolRef, shapesRef.
You do not need to solve it yet. You need to recognise the shape when it happens.
Common mistakes
await inside a forEach
// โ forEach ignores the returned promise - this does not wait
layers.forEach(async (l) => { await l.load(); });
console.log("all loaded"); // lies
// โ
await Promise.all(layers.map((l) => l.load()));
Forgetting res.ok
fetch resolving does not mean it worked. Check the status.
|| where you meant ??
const elevation = attrs.ELEV || 100; turns a legitimate 0 into 100.
Mutating an SDK object and wondering why nothing redraws Clone, modify, reassign.
Unhandled promise rejections
Every async function you call without await or .catch() can reject silently and take
your app's state with it. Chrome shows these in the console as
Uncaught (in promise). Never ignore one.
Assuming layer.fields is populated
await layer.load() first, always, if you're going to read metadata.
Exercises
Exercise 01.1 - Extend the toolkit
Add three functions to spatial-toolkit.js:
centroid(points)- the average position of an array of[lon, lat]. (Note: this is the mean centre, not a polygon centroid. Say so in a comment.)withinDistance(origin, points, metres)- filter points within a distance.chunk(array, size)- split into arrays of at mostsize. You will need this in Module 35 to batch edits under a service's limit.
Exercise 01.2 - Fix the broken code
Each of these has exactly one bug. Find and fix it.
// A
async function getNames(layer) {
const result = layer.queryFeatures({ where: "1=1", outFields: ["NAME"] });
return result.features.map(f => f.attributes.NAME);
}
// B
function averageHeight(features) {
const heights = features.map(f => f.attributes.HEIGHT || 0);
return heights.reduce((a, b) => a + b) / heights.length;
}
// C
const handles = [];
function setup(view) {
view.on("click", handleClick);
view.on("pointer-move", handleMove);
}
function teardown() {
handles.forEach(h => h.remove());
}
// D
async function loadAll(layers) {
const loaded = [];
layers.forEach(async (layer) => {
await layer.load();
loaded.push(layer);
});
return loaded;
}
A - missing await. result is a Promise, result.features is undefined.
const result = await layer.queryFeatures({ ... });
B - || 0 treats null as 0 and includes it in the average, dragging it down. Filter nulls
out instead of coercing them:
const heights = features.map(f => f.attributes.HEIGHT).filter(h => Number.isFinite(h));
if (!heights.length) return null;
return heights.reduce((a, b) => a + b, 0) / heights.length;
(Also: reduce without an initial value throws on an empty array.)
C - the handles are never captured, so teardown removes nothing.
handles.push(view.on("click", handleClick));
handles.push(view.on("pointer-move", handleMove));
D - forEach doesn't await, so loaded is empty when it returns.
await Promise.all(layers.map(l => l.load()));
return layers;
Exercise 01.3 - Parallel vs sequential, measured
Write a script that fetches three USGS GeoJSON feeds (2.5_day, 4.5_day, significant_month)
twice: once sequentially with three awaits, once with Promise.all. Use performance.now()
to time both and print the difference.
Then answer: under what circumstance would the sequential version be correct rather than just slower?
Checkpoint
- What is the difference between
const x = {}andObject.freeze({})? const { z = 0 } = { z: null }- what isz?- Why does
layer.renderer.symbol.color = "red"often not redraw the map? - What does
awaitreturn to the caller of the async function, at the moment it suspends? - You register
view.on("pointer-move", handler)in a component that unmounts. What leaks?
constprevents rebinding the name; the object's properties are still mutable.Object.freezemakes the object's own properties non-writable (shallowly).null. Destructuring defaults fire only forundefined.- The SDK's reactivity watches property assignment on Accessor objects. Deep-mutating a nested symbol doesn't trip that watch. Clone โ modify โ assign the whole renderer.
- A pending Promise. The function's remaining body becomes a continuation scheduled on the microtask queue.
- The handler closure, everything it captures (component scope, state, refs), and transitively the view and its layers - so the WebGL context and all downloaded features stay in memory.
Further reading
- https://javascript.info/ - the best free JS reference; the Promises and Modules chapters in particular
- https://developers.arcgis.com/javascript/latest/programming-patterns/ - Esri's own guide to autocasting, Accessor, promises and property watching. Read it after this module and it will make sense.
- MDN on
AbortController- you will use this more than you expect