DEV Community

Morse Zone
Morse Zone

Posted on

Build a Morse Code Trainer in JavaScript: A Weekend Project

There is a special satisfaction in decoding your first dot-dash sequence. Morse code is one of the oldest digital encodings still in use — a variable-length code from the 1830s in which frequent letters get short patterns. E is a single dot, T a single dash, while rare letters like Q (--.-) are much longer. That efficiency insight is the same idea behind Huffman coding, which makes Morse a lovely topic for a weekend coding project.

How the encoding works

Every character maps to a sequence of dots and dashes with strict timing rules:

  • A dot is one time unit; a dash is three.
  • The gap between signals within a letter is one unit.
  • The gap between letters is three units; between words, seven.

Get the timing right and your trainer will feel like the real thing. Get it wrong and "SOS" (... --- ...) turns into soup.

The trainer in about 30 lines

Start with a lookup table and an encoder:

const MORSE = { A: ".-", B: "-...", C: "-.-.", D: "-..", E: ".",
  F: "..-.", G: "--.", H: "....", I: "..", J: ".---",
  K: "-.-", L: ".-..", M: "--", N: "-.", O: "---",
  P: ".--.", Q: "--.-", R: ".-.", S: "...", T: "-",
  U: "..-", V: "...-", W: ".--", X: "-..-", Y: "-.--", Z: "--.." };

const encode = (text) =>
  text.toUpperCase().split("").map((ch) => MORSE[ch] ?? ch).join(" ");

console.log(encode("HELLO")); // .... . .-.. .-.. ---
Enter fullscreen mode Exit fullscreen mode

Then drive the Web Audio API so each dot and dash becomes an audible beep. Schedule an oscillator per symbol: short blips for dots, longer ones for dashes, and silence for the gaps. Add a text input, a play button, and a quiz mode that flashes random letters for the user to identify — an instant game.

Practice ideas that actually work

  • Copy drills: play a letter, type your guess, and track your streak.
  • Farnsworth timing: keep character speed high but stretch the letter gaps while learning — it trains rhythm, not counting.
  • Real words: graduate from single letters to callsigns and common words.

Want reference material while you build? Morse Zone offers a free translator with audio playback plus learning guides — handy for checking your timing against a correct implementation.

One HTML file, a free weekend, and you will have a gadget that teaches a 180-year-old protocol. Not bad for thirty lines of JavaScript.

Top comments (0)