JavaScript(JS) JS sort words in alphabetical order

To sort an array of words in alphabetical order in JavaScript, you can use the sort() method. Here's an example:

ref‮i:ot re‬giftidea.com
let words = ["banana", "apple", "orange", "pear"];
words.sort();
console.log(words); // Output: ["apple", "banana", "orange", "pear"]

In the example above, we create an array words with four elements. We then use the sort() method to sort the elements of the array in alphabetical order. The resulting array is ["apple", "banana", "orange", "pear"].

Note that the sort() method sorts the elements of the array in place, which means it modifies the original array and does not create a new one. If you need to preserve the original array, you can make a copy of it first and sort the copy:

let words = ["banana", "apple", "orange", "pear"];
let sortedWords = words.slice().sort();
console.log(sortedWords); // Output: ["apple", "banana", "orange", "pear"]
console.log(words); // Output: ["banana", "apple", "orange", "pear"]

In the example above, we use the slice() method to make a copy of the words array, then sort the copy using the sort() method. The resulting sorted array is stored in the sortedWords variable, while the original words array is left unchanged.