Reverse Words Algorithm
Depending on the programming language and precise data type used, a variable declared to be a string may either cause storage in memory to be statically allocated for a predetermined maximal length or use dynamic allocation to let it to keep a variable number of components. A string is generally considered as a data type and is often implemented as an array data structure of bytes (or words) that stores a sequence of components, typically characters, use some character encoding.
const reverseWords = (str) => {
// Split string into words
// Ex. "I Love JS" => ["I", "Love", "JS"]
const words = str.split(' ')
// reverse words
// ["I", "Love", "JS"] => ["JS", "Love", "I"]
const reversedWords = words.reverse()
// join reversed words with space and return
// ["JS", "Love", "I"] => "JS Love I"
return reversedWords.join(' ')
}
// testing
console.log(reverseWords('I Love JS'))
console.log(reverseWords('My Name Is JavaScript'))