DEV Community

morsetranslator
morsetranslator

Posted on

How to Build a Simple Morse Code Translator in JavaScript

🚀 Introduction

Morse code is one of the oldest communication systems, but it’s still a fun and practical concept to explore—especially for developers. In this post, we’ll build a simple Morse code translator using JavaScript that can convert text into Morse code.

📡 What is Morse Code?

Morse code represents characters using dots (.) and dashes (-). Each letter and number has a unique pattern, which makes it possible to encode and decode messages.

đź§  Step 1: Create a Morse Code Map

First, define a mapping object:

const morseCodeMap = {
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: "--..",
0: "-----", 1: ".----", 2: "..---", 3: "...--",
4: "....-", 5: ".....", 6: "-....", 7: "--...",
8: "---..", 9: "----."
};
⚙️ Step 2: Convert Text to Morse Code
function textToMorse(text) {
return text
.toUpperCase()
.split('')
.map(char => morseCodeMap[char] || '')
.join(' ');
}

Example:

console.log(textToMorse("HELLO"));
// Output: .... . .-.. .-.. ---
🔄 Step 3: Decode Morse Code
const reverseMap = Object.fromEntries(
Object.entries(morseCodeMap).map(([key, value]) => [value, key])
);

function morseToText(morse) {
return morse
.split(' ')
.map(code => reverseMap[code] || '')
.join('');
}
⚡ Want a Faster Way?

If you don’t want to build everything from scratch, you can also use an online tool for instant conversion and testing.

👉 https://morsetranslator.us/

It allows quick encoding and decoding with a clean interface—useful for testing your logic or learning Morse code.

🎯 Conclusion

Building a Morse code translator is a great beginner-friendly project that helps you understand string manipulation, mapping, and logic building in JavaScript.

Whether you build your own or use an online tool, it’s a fun way to explore how classic communication systems work.

Top comments (0)