The Code for .JS ARRAY REVERSAL
//get string value from page
//controller function
let getValue = function getValue() {
document.getElementById("alert").classList.add("invisible");
let userString = document.getElementById("userString").value;
let revString = reverseString(userString);
displayString(revString);
};
//Reverse the string
//logic function
function reverseString(userString) {
let revString = [];
//reverse a string using a for loop
//index= last position in an array AKA array.length -1;
//DECREMENTING FOR LOOP:
for (let index = userString.length - 1; index >= 0; index--) {
revString += userString[index];
}
return revString;
}
//Display result to the user
//View function
function displayString(revString) {
//write to the page
document.getElementById(
"msg"
).innerHTML = `You string reversed is: ${revString}`;
//show the alert
document.getElementById("alert").classList.remove("invisible");
document.getElementById("alert").classList.remove("d-none");
}
The code is structured in three functions.
.JS ARRAY REVERSAL
Forward and Reverse. This JavaScript coding exercise takes a forward-looking string, reverses it and displays it in reverse using the power of a decrementing for loop and JavaScript.
Brief code overview:
- Initiation:
- Event listener (located in the bottom <script> tag) is triggered by a "click" on the "submit" button.
- Inputs from the user field ("User String") is passed into the "Get Value" function
- Validation:
- Not needed with this project because it accepts both words and numbers as strings
- Logic:
Within the "Reverse String" function, the following processes occur:
- The empty array, "Rev String" is created.
- The "for" loop passes the "User string" indexes and decrements(minus) the number by one until the remaining index is less than or equal to 0.
- Each produced index is pushed to the "Rev String" array and new string appears in reverse order [4, 3, 2, 1, 0] to the original string.
- The function returns the "Rev String" array.
- Display:
- Inside the "Display String" function:
- "Rev String" is passed as a parameter.
- "Rev String" results are written to alert box located on the HTML through the "msg" id, published into the template literal.
- The alert box is hidden from the user unless displaying template literal contents.