Replace if-else chains with an object lookup in JavaScript
Intermediate · 3 min read
A long chain of if (route === 'yaba') ... if (route === 'ikeja') ... is one of the first things beginners write, and it works. But every new route means another branch, and you have to read the whole chain to see what it does. A lookup table (an object that maps each route to its fare) does the same job as data, so adding a route is one line.
In this tutorial you will write the if-chain, replace it with a table, and prove the two give the same answers. Then you will ask the table for a route called toString and find a hidden problem, and fix it. You need to know what an object is and how a function returns a value.
A table is just an object
An object maps keys to values. If the keys are route names and the values are fares, the object is the fare list:
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
console.log(FARES['ikeja']); // 35000
Fares are in kobo: 350_00 is 35,000 kobo, which is ₦350. The underscore only makes it easy to read. Reading FARES[route] with square brackets uses whatever text is in route as the key. That one lookup replaces the whole chain of comparisons.
What about unknown routes?
Reading a key that isn't there gives undefined. The ?? operator gives a fallback for undefined (and null): FARES[route] ?? null means "the fare, or null if there isn't one".
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
87 A lookup table instead of an if-chain
fairReplace a chain of if (route === ...) fare checks with one object lookup. Then ask the table for a route called toString.
Stuck? Three hints, smallest first
- 1. The chain and the table should agree on every route. Prove that before trusting the table.
- 2.
FARES[route] ?? nullhandles an unknown route in one expression. - 3. An object inherits properties, so a lookup keyed on an untrusted string can hit one.
Step 1: the if-chain
function fareChain(route) {
if (route === 'yaba') return 200_00;
if (route === 'ikeja') return 350_00;
if (route === 'lekki') return 500_00;
return null;
}
console.log(fareChain('ikeja')); // 35000
console.log(fareChain('badagry')); // null
Each line compares and returns early. Nothing is wrong with it. It just grows by one line of logic per route.
Step 2: the table
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const fareTable = (route) => FARES[route] ?? null;
console.log(fareTable('ikeja')); // 35000
console.log(fareTable('badagry')); // null
The function is one line, and it never changes again. All the routes live in FARES.
Step 3: prove they agree
Before you delete the old version, check that the new one gives the same answer for every route, including an unknown one:
function fareChain(route) {
if (route === 'yaba') return 200_00;
if (route === 'ikeja') return 350_00;
if (route === 'lekki') return 500_00;
return null;
}
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const fareTable = (route) => FARES[route] ?? null;
const routes = ['yaba', 'ikeja', 'lekki', 'badagry'];
console.log(routes.every((route) => fareChain(route) === fareTable(route))); // true
every returns true only if the check passes for all items. This is a cheap habit that catches typos in a table.
Step 4: adding a route is data
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const fareTable = (route) => FARES[route] ?? null;
FARES.epe = 150_00;
console.log(fareTable('epe')); // 15000
No new branch, no change to the function. The table could even come from a file or a server.
Step 5: the leak
Now ask the table for a route called toString:
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const fareTable = (route) => FARES[route] ?? null;
console.log(typeof fareTable('toString')); // function
You never wrote a toString key, but every object inherits a few built-in properties, and toString is one of them. The lookup finds the inherited function, so ?? never fires and the caller gets a function back instead of a fare. If the route comes from a user, they can trigger this on purpose. The old if-chain never had this problem, because it only compares against the routes you listed.
Step 6: only read the table's own keys
Object.hasOwn(obj, key) is true only for keys written on the object itself, not inherited ones:
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const safeTable = (route) => (Object.hasOwn(FARES, route) ? FARES[route] : null);
console.log(safeTable('toString')); // null
console.log(safeTable('lekki')); // 50000
Now the table is safe and still finds every real route. Another option is a Map, built with new Map(Object.entries(FARES)), which has no inherited keys to trip over.
The full solution
The answer panel has both versions, checks they agree on every route, adds epe to the table, and shows the toString leak and the Object.hasOwn guard that closes it. Press Run to see the output.
function fareChain(route) {
if (route === 'yaba') return 200_00;
if (route === 'ikeja') return 350_00;
if (route === 'lekki') return 500_00;
return null;
}
const FARES = { yaba: 200_00, ikeja: 350_00, lekki: 500_00 };
const fareTable = (route) => FARES[route] ?? null;
const routes = ['yaba', 'ikeja', 'lekki', 'badagry'];
const agree = routes.every((route) => fareChain(route) === fareTable(route));
// Adding a stop is now a line of data, not another branch.
FARES.epe = 150_00;
// A key nobody wrote, and the table answers anyway.
const safeTable = (route) => (Object.hasOwn(FARES, route) ? FARES[route] : null);
console.log('table says toString costs', fareTable('toString'));
console.log('guarded table says', safeTable('toString'));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the chain and the table agree on every route', agree, true);
test('a known route', fareTable('ikeja'), 35000);
test('an unknown one', fareTable('badagry'), null);
test('the new stop needed no new branch', fareTable('epe'), 15000);
test('but a bare lookup leaks an inherited property', typeof fareTable('toString'), 'function');
test('the if-chain never had that problem', fareChain('toString'), null);
test('Object.hasOwn closes it', safeTable('toString'), null);
test('and still finds the real routes', safeTable('lekki'), 50000);
An if-chain grows a branch per case and has to be read top to bottom; a table is data, so adding epe is one line and the code that reads it never changes. It is also a single lookup rather than up to n comparisons, though at four routes that difference is theatre — readability is the real argument.
The leak is the price. FARES['toString'] finds the inherited function, so ?? null never fires and the caller gets something bizarre back; with an untrusted key, constructor and __proto__ are worse. Guard with Object.hasOwn, or build the table with new Map(...), or Object.create(null) for an object with no prototype at all. Object.freeze(FARES) is worth adding too once the table is settled, so nothing edits your fares at runtime.
Common mistakes
- Switching to a table without checking it. Compare old and new across every case, including unknown input.
- Using
||for the fallback. A route that costs0would be replaced.??only replaces a missing value. - Trusting a bare lookup with user input. Keys like
toStringandconstructorare inherited. Guard withObject.hasOwnor use aMap.
Try it yourself
- Add a free route
staff: 0toFARESand check thatfareTable('staff')gives0, notnull. - Turn a chain that returns greetings for
'en','yo'and'ha'into a table with a fallback of'Hello'. - Rewrite the table as a
Mapand usemap.get(route) ?? null. TrytoStringagain.