JavaScript Programming for Non-JavaScript Programmers

Written by

No technology has divided the programming community more than JavsScript, mainly because it’s the been de-facto standard for web pages since around 2012, or possibly earlier. Developers either love it or hate it. I’m in the camp that says let’s do without it. But that’s for another post.

From my experience understanding JavaScript can be a challenge if you spend the majority of your time in a non-JavaScript environment.


ur doing it rong

Basically, early on my projects began like this. You might have had similar experiences.

Most tutorials start you out in javascript with just the straight-up code, as shown below.

<html>
    <head>
        <script type="text/javascript">
            document.write.println("Hello World!");
        </script>
    </head>
    <body>
    </body>
</html>

This works. Great. If you’re anything like me you probably thought, “This is great! Now I know how to write JavaScript!”

Then I looked on Google for neat JavaScript-y things to do like changing text on when a button is pressed. So, copy, paste the code!

<html>
    <head>
        <script type="text/javascript">
            var button = document.getElementById('pressme');
            button.addEventListener('click', function () {
                alert('hello, world!');
            });
        </script>
    </head>
    <body>
        <button id="pressme">Press me!</button>
    </body>
</html>

Reading this, this makes sense. You’re telling the JavaScript engine to look in the document object (or DOM) for a button (which does exist) and then tell javascript to pop up an alert when the page is loaded! Simple!

JavaScript veterans are shaking their heads now. Here’s why this won’t work.

A LT;DR Explanation of Why This Happens

When the page loads in a browser, the browser engine loads the page and parses the content linearly. After, just saying that, you can see the problem: the browser engine can’t see the button yet!

In fact, if you look in the console, you’ll see the error message displayed.

We can get around this in 2 ways. The first way is simply to move the script portion to below the body.

<html>
    <head>
    </head>
    <body>
        <button id="pressme">Press me!</button>
    </body>
    <script type="text/javascript">
        var button = document.getElementById('pressme');
        button.addEventListener('click', function () {
            alert('hello, world!');
        });
    </script>
</html>

This is fairly standard, especially if you want to include external scripts and scripts from a CDN, since the browser engine can load the direct content of the page before waiting eons for a request from an external CDN.

Or, there’s a more JavaScript-y way to do it. The document object exists once we hit the <script> tag, so we can add a listener to the DOM.

<html>
    <head>
        <script type="text/javascript">
            document.addEventListener('DOMContentLoaded', function (e) {
                var button = document.getElementById('pressme');
                button.addEventListener('click', function () {
                    alert('hello!');
                });
            });
        </script>
    </head>
    <body>
        <button id="pressme">Press me!</button>
    </body>
</html>

Notice we need to use the DomContentLoaded event or else the code will not find the button. In this case the JavaScript engine waits until all the content of the page is loaded (essentially doing the same thing as adding the script to the bottom–except that just the code inside the event handler is executed). Because the DOM content is loaded, that means the button exists, and the button can now use a click event listener.

The Point: Rocket vs. Roadie

I’ve been realizing the way I thought about JavaScript was all wrong, mainly because JavaScript is mainly taught to web develeopers.

Most langauges you can think of as a rocket ship. You hit the EXECUTE button and things start happening. Once the program executes, everything that goes on is already there, and you’re already aware of what the input is and output should be.

Rocket Launch

Even when writing plug-ins this is true. Plug-in API usually tells you the expected input and output.

However, writing JavaScript code, you need think like a roadie for a band.

Rocket Launch

The band is the main event. The roadie is there, waiting for the next order order form the band. However, the roadie has to wait for the band’s instruction. Doesn’t matter if the roadie is the fast and efficient. Starting a stage tear-down during the climactic song set will ruin the performance and the roadie will be fired.

But, once the band asks the roadie to do something (moving equipment, testing the batteries on mics, handing out water), he knows exactly what to do and can do it without the band’s instructions.

The same analogy applies to JavaScript. With JavaScript programming you need to wait for things to happen. Especially when adding on differnet JavaScript framworks like Vue or Angular, the complexity increases, so the programmer must not expect that once you hit a button that button is considered hit.

Conclusion

Even now some aspects of JavaScript confuse or surprise me. For a language that appeared as an afterthought it has become the backbone of the web. So, for programmers who are used to Java or C++ or some other framework, you, like me, might be a little confused as to what goes on under the hood. But, hopefully, I was able to explain what goes on in a more visual way.

Did you like this article?

Did you know I'm available for hire?

Send me an email here: hireme@jordanhewitt.pro

Or connect with me in Wire: @nswered