How to recursively print the alphabet in Javascript?

234 Views Asked by At

Seen some solutions using a regular for loop, but was interested in the recursive way

maybe we can define the arr as the alphabet

let arr = ['abcdefghij(...rest_of_alphabet)`]

found this on the interwebs, would this work?

Call map() using the array [ ‘a’, ‘b’, ‘c’ ] Create a new array that holds the result of calling fn(‘a’) Return [ ‘A’ ].concat( map([ ‘b’, ‘c’ ]) ) Repeat steps 1 through 3 with [ ‘b’, ‘c’ ] Repeat steps 1 through 3 for [ ‘c’ ] Eventually, we call map() with an empty array, which ends the recursion.

3

There are 3 best solutions below

4
blex On BEST ANSWER

Here is a way:

const alphabet = Array.from({length: 26}, (x, i) => String.fromCharCode(97 + i));

function printEach(arr) {
  if (arr.length === 0) return; // If arr is empty, return
  console.log(arr.shift());     // Remove the first letter from arr and print it
  return printEach(arr);        // Deal with the remaining elements
}

printEach(alphabet);

0
jsejcksn On

A simplification of this answer, without the array:

function printAlphabet (codePoint = 97) {
  if (codePoint > 122) return; // If code point is greater than "z"
  console.log(String.fromCodePoint(codePoint));
  return printAlphabet(codePoint + 1);
}

printAlphabet();

0
Mulan On

Here's a simple recursive technique using a single charCode parameter -

const alphabet = (charCode = 97) =>
  charCode > 122
    ? ""
    : String.fromCharCode(charCode) + alphabet(charCode + 1)
    
console.log(alphabet())

// abcdefghijklmnopqrstuvwxyz

Notice the exit charCode is hard-coded to 122. We would make the function more flexible by outputting a generic charRange where the caller specifies the beginning and end of the range -

const charRange = (min, max) =>
  min > max
    ? ""
    : String.fromCharCode(min) + charRange(min + 1, max)
    
console.log(charRange(97, 122))
// abcdefghijklmnopqrstuvwxyz

console.log(charRange(65, 90))
// ABCDEFGHIJKLMNOPQRSTUVWXYZ