# How to Convert Text to Morse Code and Vice Versa Using JavaScript: A Complete Guide

> Learn to convert text to Morse code and back using JavaScript. This guide explains bidirectional mapping and lookup tables with a practical example from jisan-mia/dom-projects.

- Repository: [Jisan Mia/dom-projects](https://github.com/jisan-mia/dom-projects)
- Tags: how-to-guide
- Published: 2026-03-04

---

**You can convert text to Morse code and vice versa in JavaScript by creating bidirectional mapping objects and a generic conversion function that translates characters using lookup tables, as implemented in the jisan-mia/dom-projects repository.**

The Morse Code Translator project in the `jisan-mia/dom-projects` repository demonstrates a lightweight, vanilla JavaScript approach to real-time text-to-Morse conversion. This solution requires no external dependencies and handles both directions of translation using a single reusable engine.

## Understanding the Morse Code Mapping Architecture

The implementation relies on two complementary lookup tables stored in [`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js). One map handles Morse-to-text decryption, while the other handles text-to-Morse encryption.

### The Forward Map (Morse to Text)

The `MORSE_CODE` object stores the standard international Morse code alphabet as keys, with corresponding letters and numbers as values:

```javascript
const MORSE_CODE = {
  ".-": "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"
};

```

### The Reverse Map (Text to Morse)

To avoid maintaining two separate objects, the code generates the reverse mapping programmatically using the `odolBodolFunc` function. This creates `odolBodolMorse`, where letters map to their Morse patterns:

```javascript
const odolBodolFunc = (keys, values) => {
  let obj = {};
  for (let i = 0; i < keys.length; i++) {
    obj[values[i]] = keys[i];
  }
  return obj;
};

const odolBodolMorse = odolBodolFunc(
  Object.keys(MORSE_CODE), 
  Object.values(MORSE_CODE)
);
// Result: { A: ".-", B: "-...", C: "-.-.", ... }

```

## Core Conversion Logic

The `textToMorseOrMorseToText` function in [`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js) serves as the universal translation engine. It accepts a nested array of characters, a mapping object, and a reference to the input element for validation purposes.

### The Generic Translation Engine

```javascript
const textToMorseOrMorseToText = (letters, morseCode, inputArea) => {
  let result = [];
  for (let x = 0; x < letters.length; x++) {
    result[x] = [];
    for (let y = 0; y < letters[x].length; y++) {
      const char = letters[x][y];
      if (morseCode[char]) {
        result[x].push(morseCode[char]);
      } else {
        // Handle invalid characters
        checkInputValidation(char, inputArea);
      }
    }
  }
  return result;
};

```

This function processes input word-by-word and character-by-character, looking up each symbol in the provided map and building a nested array of results.

### Handling Text to Morse Conversion

The `onTextInput` function handles user input from the text textarea (`textAreaInput`). It normalizes input to uppercase, splits it into words and individual letters, then calls the conversion engine with the reverse map (`odolBodolMorse`):

```javascript
const onTextInput = (e) => {
  const textInput = e.value.toUpperCase();
  const word = textInput.split(" ");
  const letters = word.map(w => w.split(""));
  const textToMorse = textToMorseOrMorseToText(letters, odolBodolMorse, textAreaInput);
  const morseString = textToMorse.map(w => w.join(" ")).join("   ");
  showOutput(textInput, morseAreaInput, morseString);
};

```

Note that words in the resulting Morse code are separated by three spaces (`"   "`), while letters within words are separated by single spaces.

### Handling Morse to Text Conversion

Conversely, `onMorseInput` processes input from the Morse textarea (`morseAreaInput`). It splits the input by three spaces to identify words, then by single spaces to identify individual Morse symbols, using the forward `MORSE_CODE` map:

```javascript
const onMorseInput = (e) => {
  const morseInput = e.value;
  const word = morseInput.split("   ");
  const letters = word.map(w => w.split(" "));
  const morseToText = textToMorseOrMorseToText(letters, MORSE_CODE, morseAreaInput);
  const textString = morseToText.map(w => w.join("")).join(" ");
  showOutput(morseInput, textAreaInput, textString);
};

```

## Implementation in the DOM Projects Repository

The complete implementation resides in the `projects/morse-translator/` directory of the `jisan-mia/dom-projects` repository. The architecture cleanly separates concerns across three files:

- **[`projects/morse-translator/index.html`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/index.html)** – Contains the dual textarea layout, Morse code reference chart container, and FAQ accordion structure.
- **[`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js)** – Houses the `MORSE_CODE` dictionary, `odolBodolMorse` generator, `textToMorseOrMorseToText` engine, and event handlers `onTextInput` and `onMorseInput`.
- **[`projects/morse-translator/style.css`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/style.css)** – Provides styling for the responsive layout, animated Morse chart, and input validation states.

## Complete Working Example

To implement text to Morse code conversion and vice versa in your own project, combine the following minimal HTML and JavaScript:

```html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Text to Morse Code Converter</title>
  <style>
    textarea { width: 100%; height: 100px; margin: 10px 0; font-family: monospace; }
    label { font-weight: bold; display: block; margin-top: 10px; }
  </style>
</head>
<body>
  <label>Text Input:</label>
  <textarea id="textAreaInput" placeholder="Type text..." oninput="onTextInput(this)"></textarea>
  
  <label>Morse Code Input:</label>
  <textarea id="morseAreaInput" placeholder="... --- ..." oninput="onMorseInput(this)"></textarea>

  <script>
    // Mapping tables
    const MORSE_CODE = {
      ".-": "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"
    };

    // Generate reverse map
    const odolBodolMorse = {};
    Object.keys(MORSE_CODE).forEach(key => {
      odolBodolMorse[MORSE_CODE[key]] = key;
    });

    // Generic conversion engine
    function textToMorseOrMorseToText(letters, map, inputArea) {
      const result = [];
      for (let i = 0; i < letters.length; i++) {
        result[i] = [];
        for (let j = 0; j < letters[i].length; j++) {
          const char = letters[i][j];
          if (map[char]) {
            result[i].push(map[char]);
          }
        }
      }
      return result;
    }

    // Text to Morse handler
    function onTextInput(e) {
      const textInput = e.value.toUpperCase();
      const words = textInput.split(" ");
      const letters = words.map(w => w.split(""));
      const converted = textToMorseOrMorseToText(letters, odolBodolMorse, e);
      const morseString = converted.map(w => w.join(" ")).join("   ");
      document.getElementById("morseAreaInput").value = morseString;
    }

    // Morse to Text handler
    function onMorseInput(e) {
      const morseInput = e.value;
      const words = morseInput.split("   ");
      const letters = words.map(w => w.split(" "));
      const converted = textToMorseOrMorseToText(letters, MORSE_CODE, e);
      const textString = converted.map(w => w.join("")).join(" ");
      document.getElementById("textAreaInput").value = textString;
    }
  </script>
</body>
</html>

```

## Summary

- **Bidirectional mapping** is achieved by creating a forward object (`MORSE_CODE`) for dot-dash to letter conversion and dynamically generating a reverse map (`odolBodolMorse`) for text to Morse conversion.
- **Generic conversion engine** uses the `textToMorseOrMorseToText` function in [`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js) to handle both translation directions through parameter swapping.
- **Word separation** requires three spaces between Morse words and single spaces between letters within words, while text uses standard single spaces between words.
- **Real-time processing** is implemented via `oninput` event handlers (`onTextInput` and `onMorseInput`) that instantly update the opposite textarea as the user types.
- **Pure vanilla JavaScript** implementation requires no external libraries and runs entirely client-side in any modern browser.

## Frequently Asked Questions

### How do I handle spaces between words in Morse code?

In the `jisan-mia/dom-projects` implementation, words in Morse code are separated by three spaces (`"   "`), while individual letters within a word are separated by single spaces. When converting from text to Morse, the `onTextInput` function joins converted letters with single spaces and words with three spaces. Conversely, when parsing Morse input, `onMorseInput` splits by three spaces first to identify words, then by single spaces to identify individual symbols.

### Can I convert Morse code to text automatically as the user types?

Yes, the solution in [`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js) implements real-time bidirectional conversion using the `oninput` event. The `onMorseInput` function triggers immediately when users type or paste into the Morse textarea (`morseAreaInput`), splitting the input by three-space word delimiters and single-space letter delimiters, then mapping each symbol through the `MORSE_CODE` object to reconstruct the original text in the opposite field.

### What characters are supported in this JavaScript Morse converter?

The converter supports all standard English alphabet letters (A-Z) and digits (0-9) as defined in the `MORSE_CODE` constant within [`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js). The mapping includes 26 letters and 10 numbers using standard international Morse code symbols (dots and dashes). Special characters, punctuation, and non-English characters are not included in the base implementation, though the `textToMorseOrMorseToText` function includes validation logic that can flag unsupported characters via the `checkInputValidation` helper.

### How do I validate invalid characters during conversion?

The `textToMorseOrMorseToText` function in [`projects/morse-translator/script.js`](https://github.com/jisan-mia/dom-projects/blob/main/projects/morse-translator/script.js) includes an else clause that triggers when a character lookup fails in the mapping object. When `morseCode[letters[x][y]]` returns undefined, the code calls `checkInputValidation(letters[x][y], inputArea)`, which can apply visual feedback such as red borders or error styling to the input textarea. This allows users to immediately see which characters cannot be translated in the current character set.