JavaScript Program to Sort Words in Alphabetical Order

bookmark

// program to sort words in alphabetical order

// take input
const string = prompt('Enter a sentence: ');

// converting to an array
const words = string.split(' ');

// sort the array elements
words.sort();

// display the sorted words
console.log('The sorted words are:');

for (const element of words) {
  console.log(element);
}

 

Output

Enter a sentence: I am learning JavaScript
The sorted words are:
I
JavaScript
am
learning