the beginning of my coding journey
Tags: javascript, beginners
Published: 2022-09-11 17:19:58

Throughout the start of my coding quest, there have been many growing pains.  Some of these pains relate to my own person; such as teaching myself how to be a student after being out of school for thirteen years.  Others, as expected, come from the difficulty of learning a new language.  Like my native tongue of English, JavaScript has layers of nuance and exceptions to rules.  In this blog today I'd like to outline some of these niche cases that tripped me up when creating my very first frontend web application, for Phase-1 of the online software engineering program at Flatiron School.

First, I'd like to address working with asynchronous functionality, in this case a fetch request.

```
let fighterArray = []
console.log(fighterArray);
document.addEventListener("DOMContentLoaded", () => {
    alert("RNGesus will... CHOOSE YOUR FIGHTER!!")
    grabFighters()
    addFightersToArray()
    document.querySelector("#reset").addEventListener("click", () => {
        document.getElementById("character-select").innerHTML = "";
        fighterArray.length = 0
        console.log(fighterArray);
        grabFighters()
        addFightersToArray()
        console.log(fighterArray);
    })
    document.querySelector("#randomize").addEventListener("click", () => {
        console.log("random")
    })
    document.getElementById("theme-dropdown").addEventListener("change", (e) => {
        if (e.target.value === "dark") {
            document.querySelector("link[href='light.css']").href = "dark.css";
        }
        else {
            document.querySelector("link[href='dark.css']").href = "light.css"
        }
        }
    )
    }    
);

function grabFighters() {
    fetch("http://localhost:3000/fighters")
    .then(response => response.json())
    .then(data => data.forEach(fighter => showFighters(fighter)))
};

function addFightersToArray() {
    fetch("http://localhost:3000/fighters")
    .then(response => response.json())
    .then(data => data.forEach(fighter => fighterArray.push(fighter.id)))
}; 
```
Over the course of writing this code, I was using console.log to troubleshoot that elements were being properly selected and to ascertain if my fighterArray was being emptied and restored properly.
```
    document.querySelector("#reset").addEventListener("click", () => {
        document.getElementById("character-select").innerHTML = "";
        fighterArray.length = 0
        console.log(fighterArray);
        grabFighters()
        addFightersToArray()
        console.log(fighterArray);
```
The code above contains a console.log of the fighterArray after setting the length of the fighterArray to 0.  I expected this console.log to return an empty array with a length of 0.  However, this console.log always returned a length of 19, which is the number of values that should be present after addFightersToArray is called.  Ultimately, the EventListener was functioning properly, but I needed to comprehend why that first console.log didn't return what I expected.  Upon teaching myself to use debugging tools in Chrome, I realized its due to the asynchronous nature of the functions called using fetch.  This shows while console.log is a very strong tool while writing code and troubleshooting, there are some inherent flaws in using it solely.   

Another one of my more perplexing issues came up a little later in the process.  While I was able to find a workaround, a decision I made much earlier in my coding led to an issues properly selecting items later on down the line.
```
{
"id": 7,
"name": "Arya Stark",
"image": "https://cdn.multiversus.com/roster/arya-t.webp"
}
-------------
function addFightersToArray() {
    fetch("http://localhost:3000/fighters")
    .then(response => response.json())
    .then(data => data.forEach(fighter => fighterArray.push(fighter.name)))
}; 
```
Above is an example of an object contained within .json that I fetched during addFightersToArray.  While it was not technically a mistake, my choice to push only fighter.name rather than the whole object of fighter ended up handcuffing me a little later.  Only pushing fighter.name to the array resulted in me having to write an additional function to identify the card the information was present in.  Many of the fighter names contained spaces, so when I tried assigning them as the IDs of their corresponding cards they could not be found using interpolation.  Yes, I found out during this project that IDs with spaces while technically valid cause many hiccups when trying to select them.  I have learned that the more complex the data source, the more easily it is worked with.  If I had pushed the entire object in the array I could have easily added clear targets for selection.

I'd like to close with some general statements and anecdotes regarding my experience thus far while learning JavaScript.

- Coding is **problem solving**.  Having a routine on breaking down and analyzing the problem before writing any code is conducive to success. 
- Syntax was my number one issue when getting tripped out.  Did you close the parenthesis?  Did you omit a comma?  While VSS holds your hand as much as possible these are still very easy mistakes to make.
- Be very mindful of the scope of your variable/constants/functions.  While it is best practice to make these as globally scoped as possible, there are going to some exceptions to this.  In particular, if your page doesn't function until DOM content is loaded.  The asynchronous nature of this EventListener means they variables need to be accessed after your script fully loads.
- Any instance of code used multiple times over the course of your script should be converted into a helper function of some sort.  This will allow you to both streamline the code and for it to be cleaner and more easily readable.
- Define variables/constants/function with names that pertain to their data or functionality.  This too will present a more understandable code for your own troubleshooting or for others who are dissecting your code.
- There are a thousand ways to skin a cat.  In other words, there are going to several ways to code whatever functionality you seek.  Just because someone else took a different approach does not mean you are incorrect.  It most likely mean you conceived the problem differently.
- Don't be afraid to ask peers and instructors for assistance.  No one would be where they are in life without the help of others.
- Most importantly, in the words of a 2014 YouTube viral video that resonate in my head to this day: "Google that shit."  Can't wrap your head around a problem?  Chances are someone had that same issue long before you and there's a post on StackOverflow.
- Don't be discouraged if concepts don't stick immediately, if this old dog can learn new tricks, so can you!

Cheers to a stressful yet enlightening start on my arduous journey!

![cheers](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jinck6sq996dsf1y1tf3.gif)