Beginner JavaScript Project: How to reverse a sentence and display it on screen
Tags: webdev, javascript, beginners, tutorial
Published: 2022-11-23 20:28:17

The best way to practice your JavaScript skills is to build small projects. In this article we will build a small app that takes in a sentence and reverses it.

We will be building out this project in CodePen. [CodePen](https://codepen.io/) is a popular online code editor used by many developers around the world. It is free to use and you will need to [create an account](https://www.freecodecamp.org/news/how-to-use-codepen/#how-to-sign-up-for-a-free-account) first and then [fork the pen](https://www.freecodecamp.org/news/how-to-use-codepen/#how-to-fork-a-pen) to get started. Here is the [CodePen starter code](https://codepen.io/jessica-wilkins/pen/vYrdxWy) you will need to fork that has all of the HTML and CSS.

**Prerequisites**
All of the HTML and CSS has been provided for you and we will not be covering any of that in this tutorial. This tutorial assumes that you have basic working knowledge of HTML and CSS. If you are interested in learning about HTML and CSS, then I suggest you go through [freeCodeCamp's Responsive Web Design Course](https://www.freecodecamp.org/learn/2022/responsive-web-design/).

## Table of contents

- [The basic functionality behind the reverse a sentence project](#the-basic-functionality-behind-the-reverse-a-sentence-project)
- [Topics covered](#topics-covered)
- [Accessing HTML elements using JavaScript](#accessing-html-elements-using-javascript)
- [Creating the reverse sentence button functionality](#creating-the-reverse-sentence-button-functionality)
  - [Adding an event listener to the Reverse Sentence button](#adding-an-event-listener-to-the-reverse-sentence-button)
  - [Accessing the value from the input element](#accessing-the-value-from-the-input-element)
  - [Adding an alert for users that do not provide an input](#adding-an-alert-for-users-that-do-not-provide-an-input)
  - [Reversing the sentence using the split, reverse, and join methods](#reversing-the-sentence-using-the-split-reverse-and-join-methods)
  - [Displaying the reversed sentence and working with template strings](#displaying-the-reversed-sentence-and-working-with-template-strings)
  - [Resetting the input value after the result is displayed on the page](#resetting-the-input-value-after-the-result-is-displayed-on-the-page)
- [Conclusion](#conclusion)

## The basic functionality behind the reverse a sentence project

When you open up the [CodePen starter code](https://codepen.io/jessica-wilkins/pen/vYrdxWy), you should see this result.

![starter page](https://i.imgur.com/bT90VM2.png)

We want to build an app where a user inputs a sentence and clicks on the "Reverse Sentence" button, and the reversed sentence is displayed on the screen.

![inputting sentence](https://i.imgur.com/vW1D4ZJ.png)
![reversed result](https://i.imgur.com/Tx5O33W.png)

If the user clicks on the "Reverse Sentence" button without providing an input, then an alert with display asking them to provide a sentence.

![alert message](https://i.imgur.com/h4H9KDm.png)

## Topics covered

Here is the complete list of topics covered in this project. You can click on any of the topics and it will take you to an article or MDN link to learn more.

- [`const`](https://www.freecodecamp.org/news/javascript-variables-beginners-guide/)
- [`getElementById`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
- [`addEventListener`](https://www.freecodecamp.org/news/javascript-addeventlistener-example-code/)
- [click events](https://developer.mozilla.org/en-US/docs/Web/API/Element/click_event)
- [arrow functions](https://www.freecodecamp.org/news/arrow-function-javascript-tutorial-how-to-declare-a-js-function-with-the-new-es6-syntax/)
- [return statement](https://www.freecodecamp.org/news/javascript-return-statements/)
- [alert method](https://www.freecodecamp.org/news/how-to-build-a-javascript-alert-box-or-popup-window/)
- [strict equality `===`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality)
- [innerText](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/innerText)
- [`if` statements](https://www.freecodecamp.org/news/javascript-if-else-and-if-then-js-conditional-statements/)
- [The logical NOT (!) operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT)
- [split method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split)
- [reverse method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)
- [join method](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)
- [template strings](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals)

## Accessing HTML elements using JavaScript

Our application has three main HTML elements that we need access to in our JavaScript file. We need access to the input which contains the value for the user's sentence. We need access to the button which will be used to display the result when clicked on. And we also need access to the empty paragraph element which will display the result.

There are a few ways to access elements using JavaScript. In this project we are going to use the `getElementById` method. This method will access the HTML element that matches the id that we specify. Since id names have to be unique in an HTML document, we can be certain that we are getting back the correct element.

Here is the basic syntax for the `getElementById` method:

```js
document.getElementById(id);
```

Let's first start by accessing the `input` which has an `id` of `user-sentence`.

```js
document.getElementById("user-sentence");
```

We want to be able to assign that to a variable so we can use it later on in our program. We are going to create a `const` variable called `userSentence` and assign it the `document.getElementById("user-sentence")`. We are using the `const` keyword here because this `const` variable will not be re assigned.

```js
const userSentence = document.getElementById("user-sentence");
```

If you are curious on what this `document.getElementById("user-sentence")` returns, then I would suggest using `console.log` like this:

```js
const userSentence = document.getElementById("user-sentence");
console.log(userSentence);
```

**Note: To access the console in CodePen, click on the console button in the bottom left hand corner of the screen**

![CodePen console](https://i.imgur.com/2iYp7yD.png)

You can use `console.log` to print messages to the console output. This method comes in handy when you need to understand what your code is doing.

Now that we understand how to use `console.log`, we can remove that line from our program.

The next steps would be to access the paragraph element with the `id` of `reversed-str-result`. We can use the `getElementById` method again and assign it to a variable called `reversedStrElement`.

```js
const reversedStrElement = document.getElementById("reversed-str-result");
```

The last element we need access to would be the button with the `id` of `reverse-str-btn`. We can use the `getElementById` method again and assign it to a variable called `reversedStrBtn`.

```js
const reversedStrBtn = document.getElementById("reverse-str-btn");
```

Your first three lines of code inside the JavaScript section should look like this:

```js
const userSentence = document.getElementById("user-sentence");
const reversedStrElement = document.getElementById("reversed-str-result");
const reversedStrBtn = document.getElementById("reverse-str-btn");
```

## Creating the reverse sentence button functionality

When the user clicks on the "Reverse Sentence" button, we want to display the reversed sentence on the screen. We need to start by using the `addEventListener` method.

### Adding an event listener to the Reverse Sentence button

The `addEventListener` is used to detect events in your program and execute a function when that event has occurred. The event that we are listening for is the click event to represent when a user clicks on a button.

Below the `const` variables, let's add an event listener to our `reversedStrBtn`.

```js
reversedStrBtn.addEventListener("click", () => {
  // the rest of our functionality will go here
});
```

We can test this out by adding a `console.log` that will print the message "This button was clicked".

```js
reversedStrBtn.addEventListener("click", () => {
  console.log("This button was clicked");
});
```

Open up your console and click on the button. You should see the following result:

![logging button message](https://i.imgur.com/4NJnTsF.png)

Now that we know our button is working, we can go ahead and remove that `console.log`.

```js
reversedStrBtn.addEventListener("click", () => {
  // the rest of our functionality will go here
});
```

### Accessing the value from the input element

We need to be able to get the user's input so we can successfully reverse it and display it on the screen. We can accomplish this by adding `.value` to our `userSentence` variable.

Inside the function for our event listener, let's add a `console.log` for `userSentence.value`.

```js
reversedStrBtn.addEventListener("click", () => {
  console.log(userSentence.value);
});
```

Open up your console, type in a sentence and click on the "Reverse Sentence" button to see the value in the console.

![logging out input value](https://i.imgur.com/OZyMdyf.png)

We can remove that `console.log` and assign that user value to a `const` variable called `userValue`.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
});
```

### Adding an alert for users that do not provide an input

Before we can start reversing a string, we need to check if the user provides a value.

Below the `userValue` variable, we need to add an `if` statement. An `if` statement is a type of conditional statement that will run a block of code if the condition is true.

Here is the basic syntax for an `if` statement:

```js

if(/*condition is true*/){
    // run this code here
}
```

For our condition, we want to check if the user value is an empty string. Empty strings in JavaScript are considered [falsey values](https://developer.mozilla.org/en-US/docs/Glossary/Falsy). In `if` statements, falsey values are coerced to false. We want to use the `!` operator which reverses the boolean value (ex. true is now false, and false is now true).

This is what our `if` will look like:

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;

  if (!userValue) {
    // run this code here if condition is true
  }
});
```

The `!userValue` is basically saying run this code in the if statement if `userValue` is not false. If you don't feel comfortable with the `!` operator, then you could rewrite your `if` statement like this:

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (userValue === "") {
    // run this code here if condition is true
  }
});
```

Inside the `if` statement, we want to add an alert to let users know that they need to provide a sentence. Below that alert, we need to add the `return` statement because we want to exit our function if the user does not provide an input.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
});
```

Click on the "Reverse Sentence" button without providing an input to see the alert.

![reverse sentence alert](https://i.imgur.com/knJQk4b.png)

### Reversing the sentence using the split, reverse, and join methods

There are many different ways to reverse a string. In this project we are going to use three built in JavaScript methods.

The first step is to take our `userValue` and split that into individual characters. We can use the `split` method which takes in a string and creates an array of characters.

Add a `console.log` below our `if` statement for the split method.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  console.log(userValue.split(""));
});
```

Open up the console, provide an input and click on the "Reverse Sentence" button to see the console results.

![split method demo](https://i.imgur.com/AWfFNwl.png)

Next, we want to take that array of characters and reverse it using the `reverse` method.
**Note: I am using a method called chaining here which is used to chain multiple methods together**

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  console.log(userValue.split("").reverse());
});
```

Open up the console, provide an input and click on the "Reverse Sentence" button to see the console results.

![reverse method demo](https://i.imgur.com/ZywVPUb.png)

Lastly, we need to convert that array of characters back into a string. We can use the `join` method to accomplish this.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  console.log(userValue.split("").reverse().join(""));
});
```

Open up the console, provide an input and click on the "Reverse Sentence" button to see the console results.

![using the join method](https://i.imgur.com/E3Zb1dx.png)

We can remove the `console.log` and assign the reversed sentence to a `const` variable called `reversedSentence`.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  const reversedSentence = userValue.split("").reverse().join("");
});
```

### Displaying the reversed sentence and working with template strings

Now that we have the reversed sentence, we want to be able to display that result on the screen. We can use what are called template strings(or template literals) to inject variables inside strings. Template strings use backticks instead of double("") or single quotes('').

Here is what our template string will look like:

```js
`Reversed sentence: ${reversedSentence}`;
```

We want that value to display in the `reversedStrElement` which represents the empty paragraph element in our HTML document. We can use the `innerText` method to render the reversed sentence on the page.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }
  const reversedSentence = userValue.split("").reverse().join("");
  reversedStrElement.innerText = `Reversed sentence: ${reversedSentence}`;
});
```

### Resetting the input value after the result is displayed on the page

When the result is displayed on the page, it would be nice if the input value would clear out. We accomplish this by assigning an empty string to the `userSentence.value`.

```js
reversedStrBtn.addEventListener("click", () => {
  const userValue = userSentence.value;
  if (!userValue) {
    alert("Please provide a sentence");
    return;
  }

  const reversedSentence = userValue.split("").reverse().join("");
  reversedStrElement.innerText = `Reversed sentence: ${reversedSentence}`;
  userSentence.value = "";
});
```

Now you can test out your project with a variety of sentences and should see the reversed results.

Here is the [entire code](https://codepen.io/jessica-wilkins/pen/PoaReVj) for our project. Here is the [final working result](https://codepen.io/jessica-wilkins/full/PoaReVj).

## Conclusion

I hope you learned a lot with this beginner JavaScript project. For more JavaScript projects like these, please check out the following article:

- [40 JavaScript Projects for Beginners – Easy Ideas to Get Started Coding JS](https://www.freecodecamp.org/news/javascript-projects-for-beginners/)