Check a value against allowed options in JavaScript
Beginner · 4 min read
Lots of form fields only accept a few answers: a size of small, medium or large, a payment method, a delivery option. A dropdown in the browser limits what people can pick, but anything sent to your server can be edited on the way, so the code still has to check that the value is one of the allowed options.
In this tutorial you will check that a fare tier is economy, standard or executive, accepting stray capitals and spaces. You'll compare three places to keep the list, an array, a Set and a plain object, and find out why the object can say yes to things that were never on the list. You need to know what arrays, objects and functions are.
Asking an array "do you contain this?"
includes returns true if an array has the value in it:
const TIERS = ['economy', 'standard', 'executive'];
console.log(TIERS.includes('standard')); // true
console.log(TIERS.includes('luxury')); // false
The older way was indexOf, which returns the item's position or -1 if it isn't there. So "contains" was written indexOf(x) !== -1.
A Set
A Set is a collection where each value appears once. Its has method answers the same question as includes. For a long list it is also faster, because it doesn't have to look through every item one by one.
const TIER_SET = new Set(['economy', 'standard', 'executive']);
console.log(TIER_SET.has('economy')); // true
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
119 One of a list of allowed options
easyCheck that a fare tier is one of economy, standard or executive, tolerating stray case and spaces. Compare an array, a Set and a plain object as the place to keep the list.
Stuck? Three hints, smallest first
- 1.
includessays what you mean;indexOf(x) !== -1is the older spelling. - 2. A
Setis the right shape once the list is long. - 3. Using an object as a membership list answers yes to keys it inherited.
Step 1: tidy the input, then look it up
const TIERS = ['economy', 'standard', 'executive'];
const isTier = (value) => TIERS.includes(String(value).trim().toLowerCase());
console.log(isTier(' Executive ')); // true
console.log(isTier('luxury')); // false
console.log(isTier('')); // false
The list is stored in lowercase. Before comparing, trim() removes stray spaces and toLowerCase() flattens the capitals, so ' Executive ' matches 'executive'. String(value) makes sure the function doesn't crash if it is given something that isn't text.
Step 2: the same check with indexOf
const TIERS = ['economy', 'standard', 'executive'];
console.log(TIERS.indexOf('standard') !== -1); // true
It works, but !== -1, > 0 and >= 0 all look alike, and > 0 would wrongly say no for the item at position 0. includes says what you mean.
Step 3: an object as a list, and its trap
Some people keep the allowed options as the keys of an object and look them up with brackets:
const AS_OBJECT = { economy: true, standard: true, executive: true };
console.log(Boolean(AS_OBJECT['economy'])); // true
console.log(Boolean(AS_OBJECT['toString'])); // true
toString was never on the list, yet the object says yes. Every ordinary object inherits some built-in properties from Object.prototype, a shared parent object: toString, constructor, hasOwnProperty and others. Looking one up gives a function, and a function counts as true.
When the key is what a user sent, that's a way to sneak an invalid value past your check.
Step 4: the honest object check
const AS_OBJECT = { economy: true, standard: true, executive: true };
console.log(Object.hasOwn(AS_OBJECT, 'toString')); // false
console.log(Object.hasOwn(AS_OBJECT, 'economy')); // true
Object.hasOwn only looks at the object's own properties, the ones you wrote, and ignores anything inherited. If you do want to use an object, check membership this way.
Step 5: NaN, a small difference
console.log([NaN].includes(NaN)); // true
console.log([NaN].indexOf(NaN)); // -1
NaN ("not a number") is the one value in JavaScript that isn't equal to itself: NaN === NaN is false. indexOf compares with ===, so it can never find NaN. includes uses a slightly different comparison that treats NaN as equal to NaN, so it does. You'll rarely keep NaN in a list of options, but it's another point for includes.
Keep the list in one place
Store the options in one const, like TIERS, and use it everywhere: to build the dropdown on the page, and to check the value on the server. Then adding a fourth tier means changing one line, and the menu and the check can never disagree.
The full solution
The answer panel defines the array, the Set and the object, and checks a listed option, messy case and spaces, an unlisted option, an empty choice, indexOf, Set.has, the inherited toString, Object.hasOwn and the NaN difference. Press Run to see the output.
const TIERS = ['economy', 'standard', 'executive'];
const TIER_SET = new Set(TIERS);
const AS_OBJECT = { economy: true, standard: true, executive: true };
const isTier = (value) => TIERS.includes(String(value).trim().toLowerCase());
console.log('executive:', isTier(' Executive '), ' luxury:', isTier('luxury'));
console.log('the object route on an inherited key:', Boolean(AS_OBJECT['toString']));
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a listed option is accepted', isTier('economy'), true);
test('case and spaces are normalised away first', isTier(' Executive '), true);
test('an unlisted option is refused', isTier('luxury'), false);
test('so is an empty choice', isTier(''), false);
test('indexOf is the same check, spelled worse', TIERS.indexOf('standard') !== -1, true);
test('a Set answers the same question', TIER_SET.has('economy'), true);
test('an object as a list says yes to keys it never had', Boolean(AS_OBJECT['toString']), true);
test('hasOwn is the honest version of that', [Object.hasOwn(AS_OBJECT, 'toString'), Object.hasOwn(AS_OBJECT, 'economy')], [false, true]);
test('and includes finds a NaN that indexOf never will', [[NaN].includes(NaN), [NaN].indexOf(NaN)], [true, -1]);
The object trap is the reason this is not just includes. AS_OBJECT[value] looks like a fast membership test until value is 'toString', 'constructor' or '__proto__' — all inherited from Object.prototype, all truthy, none of them yours. With user input as the key that is a validation bypass, not a curiosity. Use includes, a Set, or Object.hasOwn (exercise 84), or build the lookup with Object.create(null) so there is no prototype to inherit from.
includes over indexOf for the same reason as exercise 112: an index comparison has three plausible spellings and only one is right. It also uses SameValueZero, so it finds NaN, which indexOf cannot because indexOf compares with === and NaN === NaN is false (exercise 100). Normalising the input before the comparison — trim, lowercase — is what turns a strict list into one a human can type into, and keeping the list in one const means the same array can populate the <select> that offered the choice.
Common mistakes
- Comparing before normalizing.
'Executive'and'executive'are different strings. Trim and lowercase first. - Using
obj[value]as a membership test. Inherited keys liketoStringpass. Useincludes, aSet, orObject.hasOwn. - Writing
indexOf(x) > 0. It misses the first item. Useincludes.
Try it yourself
- Rewrite
isTierusingTIER_SET.hasinstead ofincludes. - Write
normalizeTier(value)that returns the clean tier name, ornullif it isn't allowed. - Make an object with no inherited properties using
Object.create(null), add the three tiers, and check that'toString'is no longer found.