The KonMari method of JS: variables.
Tags: javascript, beginners, productivity, webdev
Published: 2022-08-03 17:06:00

## Have you ever
been in a mad-frenzy of code writing and you came back to it the next day and asked, "How does any of this make sense?" Have you ever looked at your code and thought it messy and unorganized? Well, there is a solution to all of your muddied code, and it's called **_variables_**.

Yes, variables are not a new concept for anyone who has even dipped their toes into computer programming, but variables are a huge helper in code consolidation. When writing out functions, think of variables as the your rooms to your home. Each room is typically dedicated to a specific purpose; the kitchen contains all your cookware, plates, silverware, while your bathroom contains all of your toiletries or self-care items. Essentially, rooms are containers for specific items with specific purposes. That's how you can start to think about using variables. If you have a function that can work on multiple features or event listeners, well then, use variables so you are not writing the same function over and over again. Let's get a closer look at this concept...

---

Say you want to display a collection of book information on a webpage. You want the user to be able to sort the books by different categories, either by book title, author, or publisher. So your book collection is set up in an array: 

```
books = [
    {
        title: "The Hunger Games",
        author: "Suzanne Collins",
        publisher: "Scholastic"
    },
    {
        title: "In Cold Blood",
        author: "Truman Capote",
        publisher: "Random House",
    },
    {
        title: "Invisible Monsters",
        author: "Chuck Palahniuk",
        publisher: "WW Norton",
    },
    {
        title: "Fight Club",
        author: "Chuck Palahniuk",
        publisher: "WW Norton",
    },
    {
        title: "The Shining",
        author: "Stephen King",
        publisher: "Doubleday",
    }
]
```

You want users to click different buttons to sort the collection by categories. After some simply HTML and DOM manipulation, with some CSS styling to pretty it up, here is what the webpage looks like: 

![Webpage Display](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z547g7hkqaovurwfjh0l.png)

Let's take a look at what the html code looks like for the buttons, this will determine how we write our functionality: 


![button code](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jj8aj69snjf2i8wecfv2.png)

Notice that each button tag has its own id. This how we can grab each button in our JavaScript. We also added an in-line 
`onclick` event listener function called "categorySort" that we will flesh out in a moment.

We _could_ simply write a function for **EACH** button that uses the `.sort()` array method to sort the book array. For instance, our function to sort by title could look something like this:

```
const sortedArray = books.sort(
        function (bookA, bookB) {
            return bookA.title.localeCompare(bookB.title)
        }
```
This is fine and it will totally work, but this function will **ONLY** work for sorting by title. We will have to write two more functions that look exactly the same in order to sort by the other categories, the only difference is our dot notation will resemble the key we want to grab (book.author and book.publisher). What if we have more categories we wanted to sort? What if each object in our array contained **_50_** keys and we wanted our webpage to be able to sort by all of these keys? Our code would start to look unnecessarily long for one simple feature. That's where our friend variable comes into play...

---

## Let's turn our key into a variable
 so we only write ONE function for all three buttons. Now let's write our code for the "categorySort" function:

We first want to declare variable that takes the id name of whichever button we press:

```
function categorySort(event) {
    const category = event.target.id
}
```
We will need to pass the event as a parameter in the function declaration so we can use it for each button. The variable `category` returns a string which will match the proper key we are trying to sort by. We can use this variable in our sort function: 

```
const sortedCategory = books.sort(
        function (bookA, bookB) {
            return bookA[category].localeCompare(bookB[category])
        }
    )
```
We declared **ANOTHER** that uses our previous variable to sort the books array. We will then pass `sortedCategory` to our `bookDisplay` function to re-render our display of books. The finished code should look like this:


![categorySort](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8h02wc5iu3fkltzpkqby.png)

**_Viola!_** We have successfully write _one_ function for each button we created. If you are interested in looking at the full code, click this [link](https://github.com/btdavis300/phase-2-blog) to view my repo to this blog post.

---

As a more complicated example, we can also use multiple variables to write one function. If you are privy to React, we can write a function that will set state to multiple states. We would like to remove one item from an array, that is passed through as a parameter, and set state. So the code can look something like this: 

```
function removeStateList(deletedItem, state, setStateFunction) {
    const updatedState = state.filter(item => item.id !== deletedItem.id)
    setStateFunction(updatedState)
  }
```
Now when we invoke the function we can pass whatever variables we want as arguments:

```
    removeStateList(selectedItemOne, stateOne, setStateOne)
    removeStateList(selectedItemTwo, stateOne, setStateTwo)
//etc...
``` 

We used three different parameters to write one function. It's coding **<u>MAGIC!</u>**

Takeaways:

1. Variables can be thought of as containers that can be used as a specific feature on your webpage.

2.  We can use variables that make our code dynamic and to keep it DRY. 

3. We can use multiple parameters in a function to avoid repetition.

Thank you for reading my post about variables. See you next time!