Implementing Caesar Cipher in JavaScript

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore the Caesar cipher, a simple encryption algorithm that shifts each letter of a given string by a certain number of positions down the alphabet. We will implement the Caesar cipher in JavaScript, using a combination of string manipulation and array methods, and learn how to encrypt and decrypt messages with this technique. This lab is an excellent opportunity to practice your JavaScript skills and gain a better understanding of encryption algorithms.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/cond_stmts("`Conditional Statements`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/spread_rest("`Spread and Rest Operators`") subgraph Lab Skills javascript/variables -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} javascript/data_types -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} javascript/arith_ops -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} javascript/comp_ops -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} javascript/cond_stmts -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} javascript/higher_funcs -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} javascript/spread_rest -.-> lab-28183{{"`Implementing Caesar Cipher in JavaScript`"}} end

Caesar Cipher

To use the Caesar cipher, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Call the caesarCipher function with the string to be encrypted or decrypted, the shift value, and a boolean indicating whether to decrypt or not.
  3. The caesarCipher function uses the modulo (%) operator and the ternary operator (?) to calculate the correct encryption or decryption key.
  4. It uses the spread operator (...) and Array.prototype.map() to iterate over the letters of the given string.
  5. It uses String.prototype.charCodeAt() and String.fromCharCode() to convert each letter appropriately, ignoring special characters, spaces, etc.
  6. It uses Array.prototype.join() to combine all the letters into a string.
  7. If you want to decrypt an encrypted string, pass true to the last parameter, decrypt, when calling the caesarCipher function.

Here is the code for the caesarCipher function:

const caesarCipher = (str, shift, decrypt = false) => {
  const s = decrypt ? (26 - shift) % 26 : shift;
  const n = s > 0 ? s : 26 + (s % 26);
  return [...str]
    .map((l, i) => {
      const c = str.charCodeAt(i);
      if (c >= 65 && c <= 90)
        return String.fromCharCode(((c - 65 + n) % 26) + 65);
      if (c >= 97 && c <= 122)
        return String.fromCharCode(((c - 97 + n) % 26) + 97);
      return l;
    })
    .join("");
};

Here are some examples of how to use the caesarCipher function:

caesarCipher("Hello World!", -3); // 'Ebiil Tloia!'
caesarCipher("Ebiil Tloia!", 23, true); // 'Hello World!'

Summary

Congratulations! You have completed the Caesar Cipher lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like