DEV Community

Naftali Kulik
Naftali Kulik

Posted on • Updated on

Academic vs Intuitive Understanding Part II: Speaking the Language

When I was a kid, I always pictured a computer programmer as someone sitting hunched over a black and white screen feverishly punching indecipherable combinations of letters and numbers into their keyboard, filling up line after line with what was essentially memorized gibberish. To my mind, the word "code" evoked images of a vast and immutable library of "codes", random character combinations intended to be entered into some part of a computer that I had never seen before to make my computer's programs do the stuff they were supposed to do. Let's just say that the idea of doing something like that for a living never really appealed to me much. The more I learn, the more I see how wrong I was about all that. Well, everything other than the part about sitting hunched over a screen all day. Code is flexible, versatile, and above all, it actually makes sense. Asking a program if 1 + 1 === 2 does exactly what you would expect it to do, and the built-in methods (specifically in JavaScript, I don't know anything else yet) have names that pretty much tell you exactly what they're doing. Want to find a specific element in an array? Well, chances are that even if you know nothing at all it won't take a genius to guess that the method called .find() might be the one that you're looking for. And it's not just the names. Digging under the hood of built-in JavaScript methods shows that they follow an intuitive and logical (if sometimes complicated!) process to do what they do. The fact that it's called a programming "language" is no coincidence. Language is fluid and flexible, and one can use language to express anything, often in multiple ways. To be fluent in a language is not to have a memorized list of words in your head, rather it's about having an intuitive grasp of how it works, allowing you to manipulate the language to express yourself in the way that you want. One who is not fluent in a language cannot express themselves in that language nearly as well, even if they have memorized many individual words. Making the jump from knowledge to fluency is something that can only be done with practice, which was something that I explored in detail in my first post.

I am not claiming to be anywhere near "fluent" in JavaScript. I am still a relative beginner who is learning new things every day. However, I am starting to see growth. At the time that I wrote Part I, testing code was more about seeing what would go wrong than it was about seeing if it'd work. Working on my first major project for Flatiron School, I was pleasantly surprised that for the most part, my code did what I thought it would do the first time. I definitely ran into my fair share of bugs, but most of the time it was either something I overlooked or something written early on in the program coming back to bite me later on.

As I've become more fluent, I find myself able to manipulate JavaScript in different, creative ways to accomplish my goals. For example, if you're dealing with multiple fetch requests that all do different things, you can write out a bunch of different requests with the appropriate callbacks, or you can write something like this:

function handleGet(url, callback) {
    fetch(url)
    .then(res => res.json())
    .then(data => callback(data))
}
Enter fullscreen mode Exit fullscreen mode

this:

class Config {
    constructor(method, body) {
        this.method = method,
        this.headers = {
            "Content-type": "application/json",
            "Accept": "application/json"
        },
        this.body = JSON.stringify(body)
    }
}
Enter fullscreen mode Exit fullscreen mode

and this:

function handlePostPatch(source, method, obj, callback) {
    let url
    method === 'POST' ? url = source : url = `${source}/${obj.id}`
    fetch(url, new Config(method, obj))
    .then(res => res.json())
    .then(data => callback(data))
}
Enter fullscreen mode Exit fullscreen mode

Now all you have to do is build the appropriate callbacks and pass them as arguments in the above functions as needed. As a side point, in reference to what I wrote earlier about JavaScript methods generally having easy-to-understand names, sometimes that name sounds like it was the first thing that popped into the head of the person who developed it. I bring this up now because seriously, stringify?? It's still pretty self-explanatory though, so who cares? I definitely don't.

I'd like to share another neat trick that, while it probably wouldn't usually be necessary, demonstrates how disparate techniques can be combined to do what needs to be done in creative ways. Let's outline a hypothetical case. Say you have an app that renders data obtained from different sources, for example, information about books. Many or all of them were assigned a specific className when they were rendered to the DOM, and now you want to iterate over the HTMLCollection for that className to add some sort of event listener that would send data via a PATCH request, perhaps the contents of a <form>, and update the server accordingly. The problem you may be running into now is that to send a PATCH you need the id of whatever it is that you are updating. That may have come back as part of the request that originally was made to render the information, but how can you store that somewhere where it can be easily accessed and associated with the correct element? Generally, you'd add the event listener whenever the element was rendered to the DOM, while you're still working with the server's response and have access to the id. For argument's sake, let's say that isn't possible or practical for some reason or the other. How and where can you store the id in a way that it'd be associated with the correct element when the event listener is fired? One way to do this would be to create an object that contains the element and id in the callback that handles the original response and to push the object into an array. Then your event listener callback can iterate over the array to find the id that's matched with the correct element and use it for the PATCH. However, this involves a lot of iteration, so maybe instead of iterating over the HTMLCollection for the relevant className, maybe you can iterate over the array of objects itself to add the event listener and have the id right there. Then you'd end up with something like this:

bookArr.map(bookObj => {
    bookObj.book.addEventListener('submit', () => {
        callback(bookObj.id)
    })
})
Enter fullscreen mode Exit fullscreen mode

But there's a way to do this without creating a whole new array, by creatively manipulating strings.

Quick disclaimer, many of these string methods use iteration under the hood, so there's a good chance this isn't any more efficient than the methods I just presented, and perhaps even less so. I just think it's a cool demonstration of the diverse things you can do with different methods. I still haven't fully wrapped my brain around how Big O notation works, so take anything I say about efficiency with a grain of salt.

While handling the original request and rendering it to the DOM, add an id to the element that you are planning to add an event listener to that looks something like this (assuming data is the object from the server response that you are currently handling):

submitForm.id = `form-for-${data.id}`
Enter fullscreen mode Exit fullscreen mode

Then, in the event listener callback just to this:

const idSplit = event.target.id.split('-')
const id = idSplit.slice(idSplit.length - 1)
Enter fullscreen mode Exit fullscreen mode

There's your id! Ok fine, it's not really any more efficient than the previous methods, but it's still cool.

The more you practice, the more you become "fluent" in JavaScript. The more fluency you have, the more versatile and flexible your code can become. Eventually, perhaps writing code can become as natural as talking or writing in your native language, and creating functional applications will just become a matter of "telling" JavaScript what you want to be done, in a smooth and efficient manner.

Edit 5/27/22: There's a lot I still have to learn, such as the name attribute which would probably render my little trick with the id completely pointless. I believe that the point I was trying to make is still valid though.

Oldest comments (0)