Build a USSD menu with switch in JavaScript
Advanced · 4 min read
Dial a bank code like *901# on a phone and a little text menu pops up: 1 Balance / 2 Airtime / 3 Transfer. You press a key, a new screen appears, you press another key. That kind of menu is called USSD, and it works on any phone, with or without data.
In this tutorial you will write the logic behind such a menu as one function, step(screen, key). It takes the screen you are on and the key you pressed, and returns the next screen and the text to show. You'll build it with switch. You need to know functions, objects and return. switch is explained from the start.
A switch in a nutshell
A switch compares one value against a list of cases and runs the code under the first one that matches. default runs when nothing matches.
function dayName(n) {
switch (n) {
case 0: return 'Sunday';
case 6: return 'Saturday';
default: return 'a weekday';
}
}
console.log(dayName(0)); // Sunday
console.log(dayName(3)); // a weekday
Two things about switch matter in this exercise.
First, it compares with ===, strict equality. So case '1' matches the text '1' but not the number 1.
Second, it falls through. Once a case matches, JavaScript keeps running the lines below it, into the next cases, until it hits a break or a return. That sounds like a trap, and it often is. But it also lets several cases share one piece of code:
function kind(day) {
switch (day) {
case 'Sat':
case 'Sun':
return 'weekend';
default:
return 'weekday';
}
}
console.log(kind('Sat'), kind('Sun'), kind('Mon')); // weekend weekend weekday
'Sat' matches, has no code of its own, and falls through to the return under 'Sun'.
The plan: screens and keys
Each screen has a name, like 'menu' or 'airtime'. Our function looks at the screen and the key and returns an object such as { screen: 'balance', prompt: 'Balance: N12,450.00' }. Nothing is stored between calls. Everything the function needs comes in through its two arguments, which makes it easy to test.
Here is the exercise. Try it on your own first if you like, or read on and we will build it together.
144 A USSD menu driven by switch
hardModel a bank's *901# menu as a function of the screen you are on and the key pressed, returning the next screen and its prompt. Use switch, group the screens that behave the same way, and make an unrecognised key leave you where you are with a complaint rather than crashing.
Stuck? Three hints, smallest first
- 1. One
switchon the screen, and inside the menu screen another on the key. - 2. Every branch returns, so no
breakis needed — and none may be forgotten. - 3.
switchcompares with===, socase '1'will not match the number 1.
Step 1: the main menu
Start with one screen. On 'menu', a second switch looks at the key:
const MENU = '1 Balance / 2 Airtime / 3 Transfer';
function step(screen, key) {
switch (screen) {
case 'menu':
switch (key) {
case '1': return { screen: 'balance', prompt: 'Balance: N12,450.00' };
case '2': return { screen: 'airtime', prompt: 'Enter amount in naira' };
case '3': return { screen: 'transfer', prompt: 'Enter 10-digit account' };
default: return { screen: 'menu', prompt: 'Invalid choice. ' + MENU };
}
default:
return { screen: 'menu', prompt: MENU };
}
}
console.log(step('menu', '1').screen); // balance
console.log(step('menu', '9').prompt); // Invalid choice. 1 Balance / 2 Airtime / 3 Transfer
Every case returns, so no case can fall into the next one and we never need break. A wrong key, like 9, keeps you on the menu with a message instead of crashing.
Step 2: a screen that reads an amount
On the airtime screen the key is an amount the person typed, like '500'. We turn it into a number and check it:
function airtime(key) {
const amount = Number(key);
if (!Number.isInteger(amount) || amount < 50) return { screen: 'airtime', prompt: 'Minimum is N50' };
return { screen: 'confirm', prompt: 'Send N' + amount + ' airtime? 1 Yes / 2 No' };
}
console.log(airtime('500').prompt); // Send N500 airtime? 1 Yes / 2 No
console.log(airtime('20').prompt); // Minimum is N50
console.log(airtime('abeg').prompt); // Minimum is N50
Number('abeg') is NaN, and Number.isInteger(NaN) is false, so text that isn't a number is caught by the same check as an amount that's too small. In the real step, this code sits inside case 'airtime': { ... }. The curly braces give the case its own block, so the const inside it belongs to that case only.
Step 3: the whole function
Now add the confirm screen and the screens that have nothing left to do:
const MENU = '1 Balance / 2 Airtime / 3 Transfer';
function step(screen, key) {
switch (screen) {
case 'menu':
switch (key) {
case '1': return { screen: 'balance', prompt: 'Balance: N12,450.00' };
case '2': return { screen: 'airtime', prompt: 'Enter amount in naira' };
case '3': return { screen: 'transfer', prompt: 'Enter 10-digit account' };
default: return { screen: 'menu', prompt: 'Invalid choice. ' + MENU };
}
case 'airtime': {
const amount = Number(key);
if (!Number.isInteger(amount) || amount < 50) return { screen: 'airtime', prompt: 'Minimum is N50' };
return { screen: 'confirm', prompt: 'Send N' + amount + ' airtime? 1 Yes / 2 No' };
}
case 'confirm':
switch (key) {
case '1': return { screen: 'done', prompt: 'Request sent. You will get an SMS.' };
case '2': return { screen: 'menu', prompt: MENU };
default: return { screen: 'confirm', prompt: 'Answer 1 or 2' };
}
case 'balance':
case 'transfer':
case 'done':
default:
return { screen: 'menu', prompt: MENU };
}
}
console.log(step('confirm', '1').screen); // done
console.log(step('done', '').screen); // menu
console.log(step('nonsense', '1').screen); // menu
The last four labels are stacked, like the weekend example. 'balance', 'transfer' and 'done' all fall through to one return that sends you back to the menu. That's fallthrough doing useful work: three screens, one behavior, no copied code.
default sits in the same stack. A screen name nobody wrote a case for, perhaps saved by an older version of the app, still gets a sensible answer instead of undefined.
Step 4: replay a whole session
Because step only depends on its arguments, a whole session is just the keys pressed, one after another. reduce feeds each result into the next call. Add these lines below the step function from Step 3:
const walk = (keys) => keys.reduce((at, key) => step(at.screen, key), { screen: 'menu', prompt: MENU });
console.log(walk(['2', '500', '1']).screen); // done
console.log(walk(['2', '20']).prompt); // Minimum is N50
walk starts on the menu. For the first list it presses 2, types 500, then presses 1, and ends on done. The second list types an amount that's too small, so the session is still waiting on the airtime screen. Replaying keys like this is how you test a whole journey in one line.
Step 5: the number 1 is not the text '1'
function pick(key) {
switch (key) {
case '1': return 'balance';
default: return 'menu';
}
}
console.log(pick('1')); // balance
console.log(pick(1)); // menu
switch uses ===, and 1 === '1' is false. A USSD key always arrives as text, so the fix is to make sure input is text when it comes in (String(key)), not to add case 1: next to every case '1':.
The full solution
The answer panel has the full step function and walk, and replays one airtime purchase. The checks cover each screen, wrong keys, the strict-equality trap, the grouped screens and an unknown screen. Press Run to see the output.
const MENU = '1 Balance / 2 Airtime / 3 Transfer';
function step(screen, key) {
switch (screen) {
case 'menu':
switch (key) {
case '1': return { screen: 'balance', prompt: 'Balance: N12,450.00' };
case '2': return { screen: 'airtime', prompt: 'Enter amount in naira' };
case '3': return { screen: 'transfer', prompt: 'Enter 10-digit account' };
default: return { screen: 'menu', prompt: 'Invalid choice. ' + MENU };
}
case 'airtime': {
const amount = Number(key);
if (!Number.isInteger(amount) || amount < 50) return { screen: 'airtime', prompt: 'Minimum is N50' };
return { screen: 'confirm', prompt: 'Send N' + amount + ' airtime? 1 Yes / 2 No' };
}
case 'confirm':
switch (key) {
case '1': return { screen: 'done', prompt: 'Request sent. You will get an SMS.' };
case '2': return { screen: 'menu', prompt: MENU };
default: return { screen: 'confirm', prompt: 'Answer 1 or 2' };
}
// Three screens with nothing left to do, grouped rather than repeated.
case 'balance':
case 'transfer':
case 'done':
default:
return { screen: 'menu', prompt: MENU };
}
}
const walk = (keys) => keys.reduce((at, key) => step(at.screen, key), { screen: 'menu', prompt: MENU });
console.log('*901# then 2, 500, 1 ->', JSON.stringify(walk(['2', '500', '1'])));
console.log('a mistyped key ->', step('menu', '9').prompt);
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('pressing 1 shows the balance', step('menu', '1'), { screen: 'balance', prompt: 'Balance: N12,450.00' });
test('an unknown key keeps you on the menu and says so', [step('menu', '9').screen, step('menu', '9').prompt.startsWith('Invalid')], ['menu', true]);
test('the number 1 is not the string 1, because switch uses strict equality', [step('menu', 1).screen, 1 === '1'], ['menu', false]);
test('airtime takes an amount and asks for confirmation', step('airtime', '500'), { screen: 'confirm', prompt: 'Send N500 airtime? 1 Yes / 2 No' });
test('too little, or not a number, and it asks again', [step('airtime', '20').prompt, step('airtime', 'abeg').prompt], ['Minimum is N50', 'Minimum is N50']);
test('the whole journey ends at done', walk(['2', '500', '1']).screen, 'done');
test('saying no at the confirmation drops back to the menu', step('confirm', '2').screen, 'menu');
test('the three finished screens all fall through to the same handling', ['balance', 'transfer', 'done'].map((s) => step(s, '').screen), ['menu', 'menu', 'menu']);
test('and a screen nobody wrote a case for does not crash', step('nonsense', '1'), { screen: 'menu', prompt: MENU });
Modelling a menu as (screen, key) => nextScreen is the useful idea here. There is no state hidden in variables, so any journey is a fold over the keys pressed — the walk helper is three lines and can replay a whole session. That is what makes a flow like this testable at all, and it is the same shape a reducer takes.
Every branch returns, which is deliberate. switch falls through by default, so a break left out anywhere silently runs the next case's code; returning from each branch makes falling through impossible rather than merely unlikely. Where fallthrough is wanted, as with the three finished screens stacked above one shared return, it is doing real work: three labels, one behaviour, no repetition.
Two details that matter more in production than they look. switch compares with ===, so a key that arrives as a number matches no case '1' — USSD input is always text, and coercing at the boundary is the fix, not case 1: as well. And the default in the outer switch is a real requirement: a session can resume on a screen an older version of the code wrote, and a menu that returns undefined for an unknown screen crashes the next line up.
Common mistakes
- Leaving out
breakorreturn. The next case's code runs too, without any error to warn you. - Writing
case 1:for input that is text. It never matches'1', becauseswitchcompares with===. - Leaving out
default. An unexpected screen or key falls out of theswitch, and the function returnsundefined.
Try it yourself
- Add
4 Datato the menu, with its own screen that asks for a bundle size. - On the transfer screen, accept only exactly 10 digits. Hint:
/^\d{10}$/.test(key). - Let
0on any screen go back to the menu. Where is the neatest place to check for it?