The Code
JavaScript
//start/main/controller function function getValues(){ //get value(s) from the page document.getElementById("alert").classList.add("invisible"); let userString = document.getElementById("userString").value; let revString = reverseString(userString); displayString(revString); } //logic function function reverseString(userString){ //reverse the string let revString = []; //reverse the string using a for loop for (let index = userString.length - 1; index >= 0; index--) { revString += userString[index]; } return revString; } //view function function displayString(revString){ //display the reversed string document.getElementById("msg").innerHTML = `Your string reversed is: ${revString}`; document.getElementById("alert").classList.remove("invisible"); }
This code displays without error thanks to: https://tohtml.com
An explanation:
The code is structured in 3 parts:
getValues()
Upon the button click, getValues reads the String entered on the page.
The string is assigned to a variable and passed to the reverseString fucntion.
It also sets up the default alert behavior.
reverseString()
reverseString takes the passed parameter and runs it through a deprecating for loop, before returning a new string based on the results of the process.
displayString()
displayString sends the new string back to the page's 'msg' element.
The behavior of the alert is set to visible, thus displaying the result.
This code is linear and so completes without interaction beyond the button click.