DEV Community

TakDevelops
TakDevelops

Posted on

Career Pivot into Development Journal, Day 5: JS Practice 3 – reverseString.js

On to the next exercise...


Understanding the problem

Create a function that takes a user’s string input and reverses the string. For example. reverseString(’hello there’) returns 'ereht olleh’


Plan

  • Does program have a UI? What will it look like? What functionality will the interface have? Sketch this out on paper. The program does not have a UI. It’ll run in the console.
  • What are the inputs? Will the user enter data or will you get input from somewhere else? The user will input a string when prompted
  • What’s the desired output? The reverse of the string that the user inputed

Pseudocode

Declare a function `reverseString` that takes the parameter `string`

Create a loop that splices out each character of the string, starting from the last character

Concatenate each character at every loop and store this in a variable called `stringReversed`

Return `stringReversed`

prompt the user to enter a string and store it in a variable called `string`

Call the function `reverseString(string)`
Enter fullscreen mode Exit fullscreen mode

Divide and Conquer

Declare a function reverseString that takes the parameter string

const reverseString = function(string) {}
Enter fullscreen mode Exit fullscreen mode

Create a loop that splices out each character of the string, starting from the last character

for (i = string.length - 1; i >= 0; i--) {}
Enter fullscreen mode Exit fullscreen mode

We set the first loop to begin at the last character of the string. string.length gives the number of characters in a string, but the actual index of the last character is string.length. We run the loop until the last character which is at index 0.

Concatenate each character at every loop and store this in a variable called stringReversed

let stringReversed = '';

stringReversed += string[i];
Enter fullscreen mode Exit fullscreen mode

Return stringReversed

return stringReversed;
Enter fullscreen mode Exit fullscreen mode

Prompt the user to enter a string and store it in a variable called string

string = prompt('Enter a word or short sentence below');
Enter fullscreen mode Exit fullscreen mode

Call the function reverseString(string)

reverseString(string);
Enter fullscreen mode Exit fullscreen mode

Putting it all together

const reverseString = function(string) {
    let stringReversed = '';
    for (let i = string.length -1; i >= 0; i--) {
        stringReversed += string[i];
    }
    return stringReversed;
};

string = prompt('Enter any word or short sentence below');
reverseString (string);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)