How To Use Your Browser’s Developer Tools

How To Use Your Browser's Developer Tools

It is difficult to become an effective web developer. One way to make it easier is to leverage the technology available to you, like your browser’s developer tools.

Learning how to use your browser’s developer tools is very important. You will find these tools very helpful when working through my JavaScript tutorials. They can be used for experimenting, debugging issues, and generally seeing what’s going on behind the scenes. In this post I’m going to show you some of the most useful things you can do with them.

I’ll be using Google Chrome, but any browser will have similar tools available. In Chrome, you can open up your browser’s developer tools using several different methods. The quickest method is probably using the keyboard shortcut, Ctrl + Shift + I. Since you’re presumably reading this post in your web browser, go ahead and do that right now.

Once you have the developer tools opened up you’ll notice a toolbar at the top. There are many tabs, and all have their uses. The ones I use most often are the Elements, Console, and Sources tabs.

There are also two little icons in the top left. One let’s you jump to any HTML element on the page, and the other let’s you see what the page would look like on a mobile device. I find those little buttons helpful too.

Here is a screenshot pointing all this out.

How To Use Your Browser's Developer Tools - A Google Chrome Diagram

Elements

The Elements tab will let you make changes in real time to the HTML and CSS. This is handy because it let’s you try out changes before adding them to your HTML or CSS file. It speeds up development and allows you to iterate faster.

Just make sure you don’t get carried away. It’s possible to make a whole bunch of changes in here, but they will get reset if you refresh the page. Make sure you add your changes to the code itself if you want to keep them permanently.

Changing page elements with your browser's developer tools

Console

The Console tab lets you execute arbitrary JavaScript code in the console. This is helpful for testing things out and inspecting the contents of variables in real time.

For example, we can see below what is contained inside the answers array in the code I wrote for the ear trainer tutorial. Just type the name of the variable you want to inspect in the console and press enter.

Utilizing the console in your browser's developer tools

Sources

The Sources tab will show you the contents of your HTML, CSS, and JavaScript files.

In my opinion, the most useful thing about this tab is that you can put break points in your JavaScript code. Break points allow you to pause the execution in the middle of your running program and step through it line by line. You can also inspect the contents of different JavaScript variables that are in scope.

This is very helpful when debugging problems with your code. You can see here how I’ve set a break point at the line where we evaluate if an answer is correct. I’ve also evaluated the variables in the console so I can see if they match.

Setting break points in our JavaScript code using our browser's developer tools.

Mobile Friendly

Finally, by clicking the mobile device icon we can see a preview of what my crossword puzzle generator post looks like on a mobile device. You can choose from different device types and orientations. Testing on real devices is always the best, but this is a handy feature to make sure the page generally looks good.

Showing a mobile preview using your browser's developer tools.

You should take the time to explore more of these buttons and tabs on your own, as there is a lot of really cool and useful functionality for you to discover.

The best way to get good at using your browser’s developer tools is good old fashioned practice. Keep that in mind as a silver lining the next time you’re frustrated by a bug in your JavaScript code.

As always, thanks for reading. Follow me on Twitter if you’d like to keep up with what I’m up to.

You can also  subscribe to my blog if you’d like some tips on writing functions and to have my blog posts show up in your inbox.

Building A Crossword Puzzle Generator With JavaScript

How To Build a Crossword Puzzle Generator With JavaScript

It’s time once again for a JavaScript tutorial. This will be the most complex code I’ve introduced to date, so I hope you’ve been paying attention and not just copy and pasting! In this post you will learn how to build a crossword puzzle generator with JavaScript.

First I’ll give an introduction into what inspired this project, next I’ll discuss what the different components are and how they fit together, and finally I’ll talk about the performance optimizations I made.

You can try it out by clicking this link. Be patient after clicking the button though, as sometimes it takes a moment to create a crossword puzzle. You’ll see why soon enough. While you’re there, go ahead and use your developer tools to familiarize yourself a bit with the code.

And you can click here to check out the source code on GitHub.

A Word of Encouragement

I’ve been programming for many years now and have made lots of mistakes along the way. I like to think of myself as somebody who knows a thing or two about building software. There is an enormous number of things I don’t know, but I’m confident in my skill set and my ability to learn new concepts and technologies as needed.

However, I didn’t get that confidence overnight. I used to be pretty bad, and when I get the chance to look at some of my code from years back it makes me cringe at the silly things I did.

So if that’s you right now don’t feel bad! We all have to start from the beginning to become good at anything worthwhile.

The Source of Inspiration

And this brings me to a little a story. I created this crossword puzzle generator by porting an old Java program I wrote back when I first got out of college. I hadn’t looked at it in years, and let me tell you, it was pretty rough. You can check it out on GitHub if you want to laugh at me.

I began the porting process by going one Java method at a time. I replaced each one with a shiny new JavaScript function that replicated its logic. As I progressed I began to refactor it, fix bugs, and improve the performance.

The Fruits of My Labor

The finished product isn’t perfectly clean code, but it’s a whole lot better than it was before.

After finishing the JavaScript version of my crossword puzzle generator I began wondering to myself if it’s worth writing a tutorial for. I’m 100% certain there are better algorithms than the one I used, and I’m also 100% certain there are more readability and efficiency improvements I could make. I don’t want to teach you guys any bad habits.

It’s also very complex and not the easiest material to teach.

In the end I decided it would be a good idea. So many tutorials out there are really trivial, and don’t give you a good sense of what a typical company code base looks like. This will give you a better approximation of that. It’s a collaboration of multiple developers with varying ability levels on a fairly complex problem over many years. It just so happens that both of the developers are me. 😂

It will also give you an opportunity add your own improvements, which is key to growing as a developer.

What Exactly Are We Building?

We are building a crossword puzzle generator with JavaScript, HTML, and CSS. The idea is to take a big list of words, pick some random ones, and try to make a crossword puzzle out of them.

We’ll start by placing a word on a grid. Then we’ll get another word that is a possible candidate to connect to that word. Then we’ll do the same for another word. We’ll continue this process on an on, picking a different word each time the a word is placed or doesn’t fit anywhere in the puzzle.

When do we stop trying to place words? That’s a complicated answer determined by two main factors:

  • Have we already placed a bunch of words on the crossword puzzle?
  • Do we have a lot of word intersections on the crossword puzzle?
crossword puzzle word intersection
An example of a word intersection.

Once a crossword puzzle is made, we’ll go ahead and create some more. Then we’ll find the one with the most word intersections and show it on the screen!

Breaking Down The Problem

I won’t go into the weeds as much in this post as I do in some of my previous tutorials. There are just too many functions and edge cases to go through. Instead, I think it will be most helpful if I explain in detail the high-level components we will be creating. Knowing how all the pieces fit together is half the battle.

I really encourage you to study what each function is accomplishing while keeping in mind which variables are being changed. The comment section is a great way to reach out for help if you don’t understand something. Others will probably thank you for it.

The Big List of Words

javascript list of words

The first thing we need is a big list of words to pick from.

In my original version I pulled the King James Bible in from a text file.

In the updated version I just made a JavaScript array with a bunch of words in it. You can check it out here.

Representing a Word

To place a word on the grid we’ll need to know a few things about it. Obviously we’ll need to know the text of the word itself, but we’ll also need to know about it’s positioning. We’ll need a row and a column to mark it’s starting position. We’ll also need a boolean value to represent whether the word is horizontal or vertical in orientation.

javascript object representing a word on a crossword puzzle

We’ll represent words using a word object we create ourselves. You can check it out here.

Representing the Crossword Puzzle

The crossword puzzle objects we’re creating are representations of fully completed crossword puzzles. Each one will have various functions serving different purposes. Here is the comprehensive list of each function and what it does:

  • update: Try to add a word to the grid.
  • canBePlaced: Check if a word can be added to the grid.
  • getIntersections: Returns a count of the number of word intersections in the grid.
  • placementLegal: Determines if a word can legally be placed at a specific row/column position.
  • invadingTerritory: Determines if a word will invade another word’s territory at a certain position.
  • endOfWord: Determines if a particular row/column position corresponds to the end of the word.
  • doesCharacterExist: Determines if a character exists at a certain position.
  • overwritingHorizontalWord: Determines if placing a character at a particular row/column would be overwriting a horizontal word.
  • overwritingVerticalWord: Determines if placing a character at a particular row/column would be overwriting a vertical word
  • isInterference: Checks for interference at a set of row/column positions.
  • isLetter: Checks if there is a letter at a row/column position.
  • isEmptyCell: Checks if a row/column position is empty.
  • addWord: Adds a word to the grid.
  • fitsOnGrid: Checks if a word fits within the bounds of the grid.
  • isValidPosition: Checks if a row/column position is a valid one for the grid.

You can check it out here.

Generating the Best Crossword Puzzle

Once we have the ability to place words on a grid we need to start making a whole bunch of crossword puzzles. Then, we need to pick the best puzzle and display it on the screen. The top-level function that does all this is called createCrosswordPuzzle.

The createCrosswordPuzzle function has several nested functions that help accomplish its goals. Here is the comprehensive list of each function and what it does:

  • generateGrids: Generate a bunch of crossword puzzles.
  • attemptToPlaceWordOnGrid: Take a given a word and try to place it on the crossword puzzle.
  • getAWordToTry: Fetch a word that we want to try placing on the crossword puzzle.
  • getBestGrid: Pick the best crossword puzzle from the ones we generated.
  • isGoodWord: Determine if a word is a good candidate to try placing on crossword puzzle based on the letters on the board.
  • displayCrosswordPuzzle: Show the crossword puzzle on the screen.
  • pushUsedWords: Mark a word as used and add its letters to a list of ones present on the crossword puzzle.

In addition to the functions above, this file contains some helper functions for getting unused words and various random values.

You can check it out here.

Performance Optimizations

I hope the previous sections have helped you see how all the pieces fit together. A crossword puzzle generator is a non-trivial problem, but breaking it down into smaller problems is a good way to approach it. In fact, that’s a good approach for any programming task.

I would like to cover one more aspect in further detail. By default, this code isn’t very fast. There is a very large amount of nested looping.

I’m going to share with you the steps I took to make it faster. If you know of better algorithms I’d love for you to write me a comment. This is a life long craft, and I’m as much of a student as I am a teacher.

There are 4 steps I took to improve the performance. I’ll refer to them as Adjusting The Inputs, Smart Word Picking, Knowing When To Quit, and Calling It Good Enough.

Adjusting The Inputs

There are two variables that can have a major affect on the speed of the program. One controls the number of grids to make, and the other controls the number of attempts to fit words on the grid.

Adjusting the inputs to the crossword puzzle

I found that a high number of attempts meant that I could lower the total number of grids to make. A high number of attempts helps ensure that the crossword puzzle will be densely packed with words.

Play around with these inputs yourself and notice how they affect the speed of the program and what the crossword puzzle looks like. I tried to optimize for creating a good looking crossword puzzle while not causing the page to timeout.

Smart Word Picking

One way to speed things up is to limit our word selection to words that have a chance at being placed on the grid.

At first I picked each word totally at random, but that resulted in trying to place words on the grid that had no possible way of fitting. So I wasted a bunch of time looping through the grid, and I also wasted attempts at fitting words on the grid.

To fix this I started keeping a list of which letters exist on the crossword puzzle. That way I could limit my word selection to only words that start with one of those letters. I created the function below to aid in identifying good words to try. It isn’t perfect, but it prevents some unnecessary looping.

javascript function for smart word picking

Knowing When To Quit

Sometimes you just gotta know when to quit. As more words are added to the crossword puzzle, the likelihood of successfully placing another word goes down. There isn’t as much space for it, and the requirements for placement become stricter.

Eventually we’ll start failing for an exceedingly long time to place a word on the grid. I decided it would be better to just end things at that point. If we are having trouble placing words on the grid it is probably pretty full anyways.

It’s the law of diminishing returns at work.

Here is the section of code where this takes place. The number 470 is pretty arbitrary. It seemed about right after doing some testing.

stop placing words when we start failing a lot

Calling It Good Enough

The final step I took to improve performance was to stop generating crossword puzzles once I had created one with at least 4 word intersections.

A crossword puzzle with 4 word intersections usually looks pretty good, so stopping once we have one of those cuts down on our average generation time.

See below.

breaking out when a crossword puzzle is good enough

Conclusion

Wow that was a long and tedious post. I really hope somebody actually reads this far. If you do, leave me a comment. It will make me feel better about writing all of this 😂

I hope you’ve been able to get your own crossword puzzle generator up and running. It’s a fun project with a lot of details to consider. If you can implement it yourself and understand how all the pieces work you’ll definitely be a better developer for it.

As always, thanks for reading. Follow me on Twitter if you’d like to keep up with what I’m up to.

You can also subscribe to my blog if you’d like some tips on writing functions and to have my blog posts delivered to your inbox.

Covid-19: Who Is To Blame And Why They Are The Worst

Trump vs China

Hello my dear readers. Apologies for the intentionally over the top click-bait headline. This post has nothing to do with that. I need all the readers I can get and I am not opposed to underhanded tactics.

I know most of you are here for programming content and JavaScript tutorials, and that’s what I try to consistently deliver on a haphazard, irregular basis. However, since we currently find ourselves in the midst of the apocalypse, it seems appropriate to talk about it. I’m sure historians will love to have first hand accounts of this event, so if nothing else, consider this post my contribution to the betterment of humanity. Lofty goals, I know.

I have to admit, I was hoping for more zombies and shotguns. This has to be the most boring of all doomsday scenarios. Overall though, it hasn’t affected me personally too much. I’ve been fortunate to keep my job (for now), and have been working from home the last few months. I know many have not been so lucky.

In some ways the change in routine has been good for me. I’ve been better about eating healthy and staying active each day. And for some reason, everybody is coming out of the woodwork to jump on a video call to catch up and play video games.

It’s an interesting phenomenon because nothing was stopping them from doing this before. I think we are appreciating our relationships more now that restrictions have been placed on them. I’ll be happy if that trend continues once this crisis is over.

I don’t claim to know exactly what the best course of action is. Any policy decision will have benefits and drawbacks, and it is frustrating to see politicians and media outlets pretend this is not the case.

My biggest disappointment in all this is this feeling I get that so many of the same petty divisions remain unresolved. I remember how the United States came to together as a nation in the weeks following 9/11. It didn’t last, but it was a good moment. It seems like we have bypassed that phase and went straight to assuming the worst intentions of those we disagree with.

I may be a bit too harsh with that analysis though. People act differently on social media than they do in real life. I’ve seen people making masks, donating to food banks, picking up groceries for the elderly, and using their talents to help their neighbors. That gives me hope and reminds me that the craziest people are often the most vocal. If you start feeling pessimistic about people it’s probably a good idea to get off social media and start interracting with people in your local community.

I’ll leave playing the blame game to the masochists who like dealing with angry commenters. Now that we’re in this mess, how do we get out of it? I’m sure people with more expertise can tell you all about testing, contact tracing, social distancing, flattening the curve, and all the rest. Like I said before, I don’t know exactly what the best course of action is. But I think there is a general approach that all reasonable people can agree with. Let’s look at three options:

  1. Remain fully locked down indefinitely for months on end until a vaccine is (hopefully) developed while supply chains crumble, currency becomes worthless, and millions are forced into abject poverty.
  2. Immediately release everyone to frolic around in Myrtle Beach while kissing everyone in sight.
  3. Allow businesses to open responsibly and trust people to take appropriate measures to protect the most vulnerable.

To me, option three, while an imperfect solution, seems like the only viable one. I don’t think option one can be sustained, and option two is a bad idea under normal circumstances.

Once we can be confident that hospitals will not be overrun, we need to start getting people back to work. The timelines should look different for different geographical areas, but I think that’s the direction they need to be heading in.

Covid-19 venn diagram

And that’s about as controversial as I care to be in this post. The picture above sums up my position fairly well. I hope you all are staying safe and taking the appropriate precautions. Thanks for reading. If you want to hear more from me, you can subscribe to receive an email every time I post. That happens less often than I’d like, so you won’t have to worry about being bombarded with emails.

How To Build An Ear Trainer with JavaScript

song cover music note

Hey all you cool cats and kittens! Since we are all stuck at home trying to avoid the apocalypse, I thought it would be a good time for a new programming tutorial.

Carole Baskin

I’ve heard some encouraging news that at least one teacher has been using these tutorials to keep their kids doing something constructive during the quarantines. So that has made me happy and increased my motivation to be productive.

Instead of building another game like minesweeper or hangman, this tutorial will focus on another one of my passions: music.

Click here to check out the ear trainer you’ll be building!

Click here to view the code!

I’m no professional by any stretch of the imagination, but I’ve always had love for music. Whether it was church hymns or classic rock, music was an important part of every car ride as kid, and I’m still trying to get better at singing and playing guitar (You can check out my progress if you’re interested).

Ear Training

One area I’ve been working on is my ability to recognize common music intervals, like major thirds, perfect fifths, and octaves. A common term for this is “ear training”. You can start doing this by associating the different intervals with the beginning of certain songs ( fourth = Amazing Grace, fifth = Star Wars Theme, octave = The Office Theme, etc). But my goal is for my ear to eventually recognize these intervals instantaneously.

I’ve downloaded various apps to help me do this, but it occurred to me that I could combine my passions and build one myself!

So that’s what we’ll be covering in this tutorial: how to build an ear trainer with JavaScript. For those less musically inclined, we’re also going to be using two programming techniques I haven’t covered in previous tutorials: playing audio and local client-side storage. Let’s get started! If you get lost, the full project is on github.

Making the Music

The first thing that I had to do was create the audio files. I used a program called Audacity to record myself playing various intervals on my guitar. I used a naming convention of {intervalName}{integer} in order to make the programming task easier.

You can record your own intervals and follow my naming convention, or if you’re in a hurry you can just download or point your code to the files I created. You can find them all here on my blog, or here on github.

Structure and Style

I’m not going to focus too much on describing how the page is structured and styled. I’ll leave it as an exercise for you to explore the HTML and CSS on your own. You’re welcome to ask questions in the comment section if you run into any issues with the files provided.

The main takeaways are that we have a start button, a replay interval button, a confirm answer button, a drop down list to pick our answer, and an area for displaying messages. Our JavaScript code will interact with each of these elements as the state of the test progresses.

Also, you’ll want to make sure you update any paths so that they are pointed to where your files are located. For example, if you add your own audio files, you’ll have to make sure your code is looking in the right directory for them.

Variables

Alright it is time to move on and finally start talking about the JavaScript. We’ll begin by discussing the variables that will be changed as the player progresses through the test:

let questions = [];
let answers = [];
let questionIndex = 0;
let correctAnswers = 0;
let questionCount = 20;
let beginTime = "";

As you can see, we’re initializing an two empty arrays. One array is for keeping track of the questions, and the other is for keeping track of the answers.

We’re also initializing three variables holding integers. The questionIndex variable keeps track of which question we are on, while the questionCount variable keeps track of the total number of questions. The correctAnswers variable will be updated every time an interval is guessed correctly.

Also, we have a beginTime variable which will be set when the quiz begins. This variable will help us determine if the player has beaten his/her previous high score.

Helper Functions

Next, let’s talk about some helper functions we are going to create to make our lives easier. We’ll reuse them throughout the code, so it’s best to familiarize yourself with them early on.

Play Interval

let playInterval = function( id )
{
document.getElementById(id).play();
}

This function takes the id of an html element as a parameter. It attempts to get the element by id and call play on it. This will work if the id belongs to an audio element, but you won’t have much luck if it doesn’t. The audio elements are present in the HTML document, and each one is associated with a unique audio file.

Hide

let hide = function( id )
{
  document.getElementById(id).style.display="none";
}

The hide function takes an id and sets its display property to none. We could write this every time we need it, but “hide” is much more terse and easier to read.

Show

let show = function( id, value )
{
let element = document.getElementById(id);
element.style.display = "";
if( value !== undefined )
{
element.innerHTML = value;
}
}

The show function is the opposite of the hide function in that it makes an element visible. It also has the optional ability of setting the inner HTML content of the element. If no content is provided it won’t set it to anything and the element’s content will remain unchanged.

Get Random Integer

let getRandomInteger = function( min, max )
{
   return Math.floor( 
          Math.random() * ( max - min ) ) + min;
}

This function takes a min and max value as parameters and returns a random integer lying somewhere in between them. It will include the min but not the max as possible outputs.

Get Random Index

let getRandomIndex = function()
{
return getRandomInteger( 0, 10 );
}

This function builds on the getRandomInteger function. It’s purpose is to return a random valid index. I’ve created ten audio files for each interval, with indexes ranging from 0 to 9. So we’ll pass in 0 as the min value and 10 as the max value to satisfy our requirements.

Get Random Interval

let getRandomInterval = function()
{
    let interval = getRandomInteger( 0, 5 );
    return getInterval( interval );
}

This function is similar to getRandomIndex. You’ll call this function when you want to retrieve a random interval. In the select drop down you’ll notice that we have mapped each interval type to an integer. We have five intervals: major thirds, minor thirds, perfect fourths, perfect fifths, and octaves. These correspond to the integers 0 through 4.

After getting the random integer we call a function called getInterval to get the interval object. Keep reading to find out what that function does.

Get Interval

let getInterval = function( id )
{
    id = id + "";
    let interval = { 
                     code: "third", 
                     name: "Major Third"
                   }
    switch( id )
    {
      case "0":
        interval = { 
                     code: "third", 
                     name: "Major Third" 
                   };
        break;
      case "1":
        interval = { 
                     code: "minorthird", 
                     name: "Minor Third"
                   };
        break;
      case "2":
        interval = {
                     code: "fourth", 
                     name: "Perfect Fourth" 
                   };
        break;
      case "3":
        interval = { 
                     code: "fifth", 
                     name: "Perfect Fifth"
                   };
        break;
      case "4":
        interval = { 
                     code: "octave", 
                     name: "Octave"
                   };
        break;
      default:
        // Return whatever was set as the default
    }

    return interval;
}

The purpose of this function is to retrieve the interval object for whatever interval id was passed in. An interval object consists of a code and a name. The code matches the name of the audio file without the attached index number. The name is for display purposes.

Generating the Test

Now that we have some helpful functions created, let’s start building the test itself. For starters, we are going to need some values in our questions and answers arrays. Let’s look at where this get populated, in a function called, generateTest.

How to build an ear trainer with javascript: Generate Test

This function is called when the player clicks on the start test button. The first thing that happens is we hide and show some elements on the screen. We show the question area, which includes our buttons for replaying sounds and choosing answers. We hide the start test button because at this point the test is already underway. Also, we show the message area with a non-breaking space. This is to keep the size of the container the same whether there is a message to display or not.

The next thing we do, after initializing a few local variables, is start adding questions and answers until we have reached the number set by the questionCount variable. We set each question to a random index appended to a random interval code. The random interval is then stored at the same index in the parallel answers array.

Finally, we set the beginTime of the test, and proceed to the next question by calling the appropriately named, nextQuestion function.

Proceeding to the Next Question

How to build an ear trainer with javascript: Next question function

The nextQuestion function is a pretty simple one. It does two things. First, it will show which question the player is on. Next it will play the audio file corresponding to the interval in question.

Replaying the Interval

What if the player needs to hear the interval again before answering? In that case they can trigger the replayInterval function by clicking on the replay interval button. Notice how boring my variable and function names are? That’s a good thing.

How to build an ear trainer with javascript: replay interval

This function is even simpler than nextQuestion. All we do is call play interval and pass in the current question that we are on.

Choosing an Answer

choosing a final answer for interval

The player selects his/her desired answer from the drop down list, and then clicks on the confirm answer button to guess what the interval is. When this happens, the confirmAnswer function is called.

Confirm answer function

The first thing that happens is the answer is evaluated to see if the player guess correctly. We’ll cover that function in a bit.

Next, the questionIndex is updated. If the questionIndex is less than the questionCount, we call the nextQuestion function. Otherwise, we call the finishGame function.

Evaluating the Answer

evaluating the answer for the interval

The purpose of the evaluateAnswer function is to determine if the player answered correctly and update the state of the game appropriately. Fortunately, the consequences for answering incorrectly will not be nearly as dire as in Indiana Jones.

How to build an ear trainer with javascript: evaluate answer

The first thing we do is retrieve the answer from the selected option in the drop down list. Then we get the interval object by calling getInterval.

Finally, we check if the chosen interval’s code matches the one we have stored in our answers array. If the answer is correct, we increment the correctAnswers count and don’t show a message. If the answer is wrong, we show a message to the player informing them of what the correct answer was.

Finishing the Game

How to build an ear trainer with javascript: Finish the game

After the last question has been answered we need to show the start button again and hide the question area.

Next, we need to determine the player’s score, which consists of the number of correct questions and the total time it took him/her to complete the test.

Before showing the score to the player we will determine if he/she beat his/her previous high score. This will help us determine which message to show on the screen.

We find this out by calling the saveHighScore function.

Saving a High Score

George from Seinfeld with frogger

We will be storing the high score client side in the player’s web browser. This means that the high score will persist even if the player closes their browser. This feature will allow players to compete against themselves and become faster and more accurate in their ability to guess intervals.

Save high score

We start out by assuming that the player did not beat his/her high score. After grabbing the score and time out of local storage, we check if they did beat it. We consider a score better if the player answered more questions correctly or answered the same number correctly in less time. If the player beat his/her high score, we override the values in local storage.

Conclusion

That’s it! You have successfully created your own ear trainer. You should be proud of yourself.

From here you can go in lots of different directions. I can think of so many features to add that are beyond the scope of this tutorial. You could add more intervals, descending and ascending intervals, or the ability to choose a subset of intervals you want to train on. The list goes on and on.

Have you implemented other cool feature ideas? Are you stuck on anything you saw here? I’d love to hear from you in the comments. Be sure to subscribe to stay up to date with the latest content.

NULL Values in SQL Queries

NULL Values in SQL Queries

Today’s post is about NULL values in SQL, and comes courtesy of my friend and database wizard, Kaley. You should check out his website if you’d like to learn more about SQL, Oracle database, and making queries run faster .


Here’s a topic that gets a lot of budding developers in trouble–the concept of NULL values in SQL queries.

Whenever you issue a SQL query to a database…and you want to know whether a column has a NULL value in it…what is the proper way to write a query that will find the result?

Should you use a query like this?

SELECT * FROM SOME_TABLE
WHERE SOME_COLUMN = NULL

Or! Should you use a query like this?

SELECT * FROM SOME_TABLE
WHERE SOME_COLUMN IS NULL

…The answer is, you should be using the second query (WHERE SOME_COLUMN IS NULL).

Now why is that?

We don’t use the “IS” keyword with any other comparisons in the database, right?

If we want to know if a field is equal to one, we use a WHERE clause like this:

WHERE SOME_COLUMN = 1

So why on earth would we do the IS keyword with a NULL value? Why would we need to treat NULL differently?

The answer is this: In SQL, NULL represents the concept of “unknown” (so a NULL value represents an “unknown” value).

Null as an Unknown

In most databases, there is a difference between NULL and an empty string (represented by a “double apostrophe” or ”).

But this isn’t always true for all databases:  For example, Oracle database won’t allow you to have an empty string. Anytime Oracle database sees an empty string, it automatically converts the empty string into a NULL value.

For the majority of the other databases out there, though, a NULL value is treated differently than an empty string:

  • An empty string is treated like a known value where there is no value.
  • A NULL value is treated like a value that is not known.

This would be the difference between me asking the question, “What was U.S President Theodore Roosevelt’s middle name?”

  • One answer might be, “Well, I don’t know what Theodore Roosevelt’s middle name is.” (This idea could be represented by a NULL value in the MIDDLE_NAME column for Theodore Roosevelt’s record)
  • Another possible answer could be “President Theodore Roosevelt actually didn’t have a middle name. His parents never gave him a middle name, and I know for a fact that Theodore Roosevelt didn’t have a middle name.” (You would represent that by putting an empty string, or a ” into the MIDDLE_NAME column)

Oracle database is the most notable exception where those two values are actually both going to be represented by NULL–most databases other than Oracle are going to treat NULL and an empty string very differently.

As long as you can remember that a NULL value represents an unknown value, then this is going to help you craft your SQL queries, and help you work around some of the trickier situations that you can get in with NULL values.

If, for example, you were to have a query that uses a WHERE clause like this:

SELECT * FROM SOME_TABLE
WHERE 1 = 1

This query will return rows (assuming SOME_TABLE isn’t an empty table!) because the expression “1 = 1” is provably true…it can be proven to be true.

If I were to say:

SELECT * FROM SOME_TABLE
WHERE 1 = 0

…then the database sees this and evaluates “1 = 0” as false (meaning this query would never return any rows).

But if I were to say:

SELECT * FROM SOME_TABLE
WHERE 1 = NULL

The database basically goes, “I don’t know if these two values (1 and our black-box NULL value) are equal”…so it doesn’t return any records.

Ternary Logic

When you have a WHERE clause in a SQL query, it can have one of three different results:

  • It can be true (and it will return rows)
  • It can be false (and it won’t return rows)
  • Or it can be NULL or unknown (an unknown is also not going to return values)

You may be thinking, “Okay, but why do I care that there’s a difference between false and null since the database handles those two values exactly the same?”

Well, let me show you where you can run into trouble:  Let’s introduce the NOT() condition.

If you were to say:

SELECT * FROM SOME_TABLE
WHERE NOT(1 = 1)

Then the database is first going to evaluate 1 = 1 and say, “Okay, that’s clearly true.”

But then it’s going to apply the NOT() condition to it. The database is going to go, “Well true, when notted, turns to false…so the NOT() condition causes our WHERE clause to be false here.”

So the query above isn’t going to return any records.

However, if you were to say:

SELECT * FROM SOME_TABLE
WHERE NOT(1 = 0)

Then the database first evaluates expression 1 = 0 and says, “That’s clearly false.”

But then it’s going to apply the NOT() condition, which will give us the opposite result, so it becomes true.

So this query will return records!

What if I issued the following query though?

SELECT * FROM SOME_TABLE
WHERE NOT(1 = NULL)

The database is first going to evaluate 1 = NULL. (Remember, it’s going to treat NULL like an unknown value!)

It’s going to say, “I can’t say whether or not 1 is equal to NULL because I don’t know what the NULL (unknown) value is.”

So it doesn’t yield a true result, and it doesn’t yield a false result–it instead yields a NULL (or unknown) result.

This NULL result is going to be interpreted by the NOT() operator.

Whenever you take a NULL and you put it in a NOT() condition…the result is another NULL! (the opposite of unknown is…well…another unknown).

So the NOT() operator doesn’t do anything with null conditions.

So NEITHER of these queries…

SELECT * FROM SOME_TABLE
WHERE NOT(1 = NULL)

SELECT * FROM SOME_TABLE
WHERE 1 = NULL

…is ever going to return any records…even though they’re opposites!

NULL and NOT IN

If I issued a query with a WHERE clause like this:

SELECT * FROM SOME_TABLE
WHERE 1 IN (1, 2, 3, 4, NULL)

…then clearly the WHERE clause is going to be true, and this query will return records, since 1 is in our IN list…

But if I were to say:

SELECT * FROM SOME_TABLE
WHERE 1 NOT IN (1, 2, 3, 4, NULL)

Then clearly this is going to be false, and this query will never return records, since the number 1 appears in our IN list and we’re saying “NOT IN”…

Now what if I were to say something like this?

SELECT * FROM SOME_TABLE
WHERE 5 NOT IN (1, 2, 3, 4, NULL)

This WHERE clause will never return any records, since it is not provably true (it cannot be proven to be true). The number 5 doesn’t explicitly appear in the “IN” list–But 5 could be inside our “black box” NULL value (the database doesn’t necessarily know what the value of NULL is).

This yields a NULL result (meaning an unknown result) and this WHERE clause is never going to return any records.

This is why it’s important to consider a NULL value to be equivalent to an unknown value–it’s going to help you whenever you craft complex SQL queries.

Hopefully you’re now equipped to deal with NULL values in SQL queries! For more information on SQL, Oracle database, and making queries run faster, visit blog.tuningsql.com.

A Web Developer’s Attempt to Make Pong with Unity in One Night

Pong in Unity

I’m a solid developer. Don’t get me wrong, I’m not the best in the world, but I can think logically and solve problems. Still, I find myself in awe when I look at the work produced by the giants in our field.

As a web developer I, along with millions of others, depend on a few tools conceived in the mind of Linus Torvalds. Without Linux and Git, my job would be a lot more frustrating. But Linus is only the first of many people that come to mind. So many important languages and tools are the creations of single, brilliant individuals.

Perhaps most inspiring of all, yet often overlooked, are video game developers. My theory is because they often work in large teams they don’t always get the individual credit they deserve. Guys like John Carmack and the founders of Naughty Dog have worked on the bleeding edge of technology while creating software that has brought more joy to people than the latest front end Javascript framework ever will. You should read the story of how Naughty Dog created Crash Bandicoot. It’s incredible.

Getting Inspired

I’ve always romanticized game development. I think every kid who grew up playing video games has dreamed of building a masterpiece themselves. Even as an adult I sometimes dream about undertaking such an ambitious project.

These thoughts have inspired me to delve into that world as a bit of a hobby. You all have probably seen my previous game tutorials using web technologies, but I wanted to challenge myself a bit more with something different and closer to the real thing.

I decided to build pong in one night (or two) using the Unity Engine (Version 2019.2.18f1). Unity is C# based game development engine used by a lot of indie game developers. I’ve followed some in-depth Unity tutorials in the past, but never built something on my own. Let’s just say that the finished product is not quite ready for the market, but it’s as done as I care to be for this blog post:

Unity is free to use for individuals, and you’re welcome to download my project files below and boot them up. This post won’t be a full tutorial though, just a higher level overview of what I did and what I learned as I struggled with a new development environment.

How I Made Something Kind Of Like Pong

I started by following this helpful tutorial, and then customized it to be a more complete game. I find that to be a helpful tactic when solving new problems: find somebody to hold your hand at first, and then spread your wings from there.

Main Camera

Camera for Pong

I built everything with 3D objects that I created directly in Unity. The main camera is fixed in position and used for showing the game as if it were in 2D. This trick seems like it could be useful in other games as well.

Directional Light

Directional Light

This object was there when I created the project. I assume it is providing light to the scene, but I really don’t know how important it is!

Bumper (2)

Bumpers for Pong players 1 and 2

These are controlled by players one and two and are used to hit the ball back and forth. They are controlled by the following script:

Bumper script

Every frame we check to see if we need to translate the position of the bumper. If it is within the acceptable range we translate it by a factor of the speed and input direction of the bumper as well as the time in seconds since the last frame. Otherwise we force the bumper back to within its acceptable bounds.

Wall (2)

Walls for Pong

These are the outer walls that keep the ball in play. Pretty straightforward stuff.

Background

Pong background

A big black sheet providing a background that provides contrast with the rest of the game.

Ball

Ball

The ball is what the players are hitting back and forth. It has an attached script:

Ball script

This script initializes the position of the ball in the middle of the screen and sets it off in a semi random direction. The ball object also contains a method called “Halt” which will stop the ball and fix it in the middle of the screen. This is called when the game ends.

Goal (2)

Pong goals

The goals are where the players need to get the ball to. Each goal object has this script attached:

Goal script

The script checks for collisions with the ball. On each collision it checks to see how many goals have been scored and, if the game is over, displays the winning message and stops the ball in the middle of the screen. If the game is still going on then it resets the ball to the center of the screen and sets it off in a semi-random direction.

I also included a check for user input here on every frame. There is a probably a better place to put this, but I’m just a humble web developer bumbling my way through this. You can press “r” to reset the game, and “escape” to close the game.

Score

Score

I used 3D text objects for displaying the score. They look really bad. I imagine there must be a better way to do this. Here is the script to control them:

Score script

Every frame I’m just setting the score text to the appropriate number of goals.

Winning Message

Winning Message

Finally, the last object. I’m really tired of uploading screen shots. This message is invisible until the game is over. Then it displays either player one or player 2 as the winner.

Important Project Settings

I changed a few defaults in the project settings to make everything work reasonably well.

I had to make the physics bouncy by default.

Physics settings

I also had to setup keyboard controls for player 1 and 2 via the input settings.

Input settings

Lessons Learned

  • The physics engine is powerful and can help you a lot, but I need to understand it better to use it to its fullest extent. Sometimes the ball just rolls perfectly horizontal along the wall, and I’m not sure how to fix that. I’ve even managed to get the ball to stop entirely.
  • Zero gravity was important.
  • Collision detection is easy to get wrong. I know I need to use Rigidbody objects, but I don’t totally grasp the fundamentals quite yet. I had to increase the mass of the goals to a huge number to prevent them from moving on collision with the ball. I have the feeling I’m doing something silly there.
  • I probably could benefit from researching some Unity best practices. Often I solved the problems but felt uneasy about the solutions. Maybe something like this would help.
  • The 3D text objects look really bad. I bet there is a better way to do that.
  • Some of the design patterns I learned in web development are relevant, but I get the feeling that game development requires a different way of thinking a lot of the time.
  • A trusty search engine is your friend.

Tem Tem Trailer Song Lyrics

Tem Tem Trailer Lyrics

So here’s a weird post for you guys. Recently, some friends from work and I have been making jokes about a new game by indie developers called “Tem Tem.” It is basically just Pokemon put through a thesaurus. Trainers are tamers, poke balls are tem cards, gyms are dojos, etc. I started playing it and have thoroughly enjoyed it!

There is a Tem Tem trailer with a silly theme song that is stuck in our heads, but we haven’t been able to find the lyrics to the song anywhere. Since I did the hard work of listening and writing them down, I figured I might as well post them in the off chance that anybody else is searching for them.

If you got here through Google, welcome to my blog! Since you like video games you might be interested in learning how to make them yourself. My most popular tutorial teaches you how to make minesweeper.

Tem Tem Trailer:

Song Lyrics:

We’re ready to start the combat
It’s time to reveal our Tem cards.
Let’s do it, pick the contenders,
and Tem Tem up!
We’re eager to leave.
The adventure begins.
Our destiny waits overseas.
Wisdom and faith,
focus and stealth,
honor and strength,
courage to face those who could steal our fates.
This journey will challenge us.
We’ll struggle to find and beat them all.
No matter how long is the path
of commitment to change at the end we’ll approach our goals.
Great tamers awaiting us,
all together we’ll build a bright future and Tem Tem up!

Landing and Excelling At Your First Web Development Job

First Web Development Job

I was talking to somebody the other day who had just finished up school and is looking for his first web development job. I had a lot of thoughts on the subject, but they weren’t very well organized. So I thought it would be prudent to refine them and write them down. Maybe some folks will find them useful.

This post is geared towards aspiring web developers. While there are many other great career paths to follow, such as mobile app development, game development, or embedded programming, I’m choosing to focus on a topic I’m qualified to write about.

There are two categories within this topic that, to me, seem important to address. The first is landing your first web development job, and the second is preparing yourself to be successful once you get there.

Landing The Job

General Advice

  • Create a LinkedIn Profile , and make it look professional. Follow the steps suggested on LinkedIn to create a good profile. Recruiters are very active here. You’ll have to learn to distinguish good jobs from bad ones, but what we are going for here is increasing the quantity of available opportunities.
  • Create a resume. If you’re familiar with a programming language it’s a good idea to list it. Don’t claim to be an expert if you’re not one though. You’ll be inviting questions about the topic. If you put items on your resume you should be willing and able to discuss them intelligently.
  • Prepare for interviews. Lookup common interview questions online and be prepared to answer them. Websites like leetcode have technical questions. Working through some of these questions will help prepare you for the technical portion of job interviews.
  • Often the best way to get a job is through personal contacts. Keep up with classmates, school faculty, and others in the software industry who may be able to provide you with an inside track to a good position at a company.
  • Look up local job postings and see which programming languages are in high demand. Consider focusing your efforts on learning one of those languages.
  • Have at least one personal programming project you’re proud of and can talk about. Put it on github. This is a common interview question.
  • Think about programming classes you took in college and be prepared to talk about what you liked/disliked and what you learned.
  • Show up to interviews well dressed.
  • If you are having trouble landing your first web development job, consider applying for QA positions, even if that’s not your ultimate goal. It’s a great way to get your foot in the door, and you’ll probably get the opportunity to do some programming if you show a little initiative. Good testers are worth their weight in gold, and a lateral move within the company might be easier than getting hired directly as a developer.

Questions To Ask During The Interview

  • What is the build system like? Can you build the code in one step? Do you do daily builds?
  • How is QA/testing handled? Do you have automated testing?
  • What’s the on-call situation like?
  • How many people will you be working in the same room with?
  • Do you use version control?
  • Do you use a bug tracking tool?
  • Ask for more time off if you can’t negotiate salary further.

Preparing Yourself To Be Successful

What Technology To Learn?

There is so much technology available these days to build web applications. It can be a bit overwhelming when you see the vast number of web development libraries and frameworks that exist.

My basic advice for your first web development job is to focus on learning and understanding the underlying concepts and languages. Once you do, you will have no trouble learning whatever the hot new framework is. Learn whichever frameworks your company uses, but remember that the languages they are built on are the foundation.

Much can be learned on the job, but the more you know ahead of time, the better prepared you will be. Be curious and eager to learn more. It will serve you well throughout your career.

Front End
  • HTML is for structuring the content of the web page.
  • CSS is for making the web page look pretty.
  • JavaScript is for making the page interactive and making ajax calls.
    • It’s most important to understand the language itself, but you’ll probably encounter some front end frameworks in your career. I wouldn’t worry about learning them until you have to for the job, but it’s a good idea to be familiar with them.
      • jQuery is an older library, but it used to be very popular. Don’t be surprised if you encounter it eventually.
      • Newer popular frameworks include React, Vue.js, and Angular. New ones come out all the time and we are all sick of them.
      • There are lots of related technologies, like Babel, Webpack, TypeScript, etc. Learn these as required by the job, unless you’re just really interested in them.
  • Learn how to use the browser’s developer tools.
  • I’m more of a back end guy, so take my advice with a grain of salt!
Back End
  • Understand object oriented programming. It’s a useful paradigm and very popular in the business world.
    • Knowing and understanding the buzz words is good for passing interviews. Polymorphism, Inheritance, Encapsulation, etc.
  • Popular languages: Java, C#, Python, Ruby, PHP. There are plenty of others. I’d recommend looking up what kind of jobs are most common in your area, and then focusing on learning whatever that language is.
  • Different languages have different web frameworks around them that people use. You’ll have to learn whichever one your company uses.
  • One thing common to different web frameworks is a dependency management system. In Java, for example, this is usually Maven. It’s worth learning about how these work. They’ll let you use code built by other people.
  • Learn to use your IDE well, including the debugger and its keyboard shortcuts.
Database
  • Learn how to write SQL queries. It doesn’t matter much which database vendor. They are basically all the same with some slight quirks.
  • Know select, update, insert, delete (Often referred to as CRUD operations).
  • Understand how joins, having clauses, group by clauses, and aggregate functions work.
  • Lots of companies use ORMs (Hibernate, etc) to interact with databases. These are nice to know, but less important than knowing SQL.
HTTP (Hyper Text Transfer Protocol)
  • Basically, understand how the internet works at a high level.
  • Know what a GET request is.
  • Know what a POST request is.
Version Control
  • Git is the most common one. It’s worth learning no matter which company you work for. You’ll use it eventually if you stick with this career long enough.
    • Commit
    • Pull
    • Push
    • Merging code
    • Local vs Remote
    • You can use the command line, but there are also some nice GUI applications for interacting with git. My favorite is Source Tree.
    • Learn how to use GitHub
  • Other popular ones include subversion and mercurial. Only learn these if your job requires it.
Linux

Most web servers run Linux unless they are on the Microsoft stack. And they usually don’t have a GUI. So it’s worth your while to become comfortable navigating using the command line.

Useful Books and Websites

  • Stack Overflow for finding answers to programming questions. Don’t just copy and paste. Try to understand the code.
  • Hacker News for learning about the latest trends in tech and listening to people worry about climate change. You can sometimes find job opportunities here as well.
  • Code Complete, the best book I’ve read on how to write good code. You’ll thank me and so will your peers.

Have more advice to add? I’d love to hear from you in the comment section below this article.

How To Make Appealing Game Graphics

How To Make Appealing Game Graphics

We’re taking a break from my programming series to bring you a post coming courtesy of my first guest contributor, Ashlie Lopez! She is an experienced writer who will be covering a side of building cool technology that, based on the visuals of my hangman game, I probably have no business trying to tackle. She will be discussing how to make appealing game graphics.

Enjoy!


Developing realistic and appealing game graphics is not an easy task. When a user first sees your game, his first impression is based on the art of the game. Gamers tend to form an opinion about a game based on the overall appeal and aesthetics before actually playing the game. Therefore, game developers and producers invest a major chunk of their budget into game art and design.

As a designer, there are many different areas that you need to work on to create visually stunning graphics. Your designs should give a good user experience to players and should be consistent in terms of characters, colors, backdrop etc.

Whether you are an experienced or a new graphic designer, the following are some useful tips and techniques that will help you create better visuals for your game:

Follow the principles of design

The job of a skilled graphic designer is to understand and create designs by following the principles of design. The principles of design help a designer convert various design elements into powerful visuals. In order to create correct and meaningful visuals that leave a strong impact on the user’s mind, you need follow the rules of designing:

  1. Alignment 
  2. Proportion
  3. Repetition
  4. Contrast
  5. Balance
  6. Emphasis
  7. Hierarchy
  8. Harmony
  9. Unity
  10. Proximity

As a designer, it is your job to understand each and every element and use them as powerful tools to create stunning game designs. 

Have strong layouts

A layout is the foundation of every design. As a game designer, your layouts should be well balanced and well-proportioned in order to connect with the audience’s eye. In simple words, a layout is simply the assortment of various graphical elements. A layout also ensures consistency in designs. A strong layout can help viewers to focus on gaming elements that are the most important.

Every element in a game has its own identity and significance. The value of each element depends on its position on the game’s layout along with the proportion, repetition and contrast of the element.

Add depth to gaming images

The use of depth to achieve appealing game graphics

Depth is yet another useful element of a visual image that helps to make certain images more elaborate and prominent in a game.

A designer can use depth as a powerful tool to help players get a better understanding of scale. Depth can be achieved through experimenting with lighting, outlining, and adjusting the hues and saturation of an image.

Provide unique styling

For every game, you need to come up with a new style that would give a distinctive identity to your design. You play with colors and lighting to create a new style for your design. Your graphics should be unique enough to attract the attention of gamers. Whether it is the backdrop or the characters of the game, you need to design them in such a way that they instantly create a connection with the players.

As a designer, your main goal should be to create crisp and sharp graphics. It is not necessary to create too realistic or intricate graphics to make your character stand out. Sometimes, going for a minimalist approach by creating simple characters is more effective than creating overly complex designs.

Enhance graphics with colors

Colors are the one the simplest tools for bringing images to life. In games, it is recommended to go for saturated and vibrant colors. However, every game has its own unique requirements based on its story line, characters and genre.  More vibrant and bright saturated colors work for casual or strategic games that are designed to cater to a wider audience of different age groups. Pastel colors are mostly used for fantasy video games. You can use customized video game glasses to enhance your gaming experience.

Get constructive feedback

Getting constructive feedback and criticism is a great way to know which design element works for the game and which could be replaced with a better alternative. Learning and improving your skills from feedback is a great way to keep upgrading your portfolio and stay relevant in the industry. Through feedback and suggestions, a designer gets to know about his strength and weaknesses in designing. The best and most honest review that a game designer could get is from the gamers themselves.

Programming Languages For Beginners

Programming Languages For Beginners

In the last post we discussed the topic of algorithms. That was fun and all, but how do we turn them into useful programs? That is where programming languages come in. The goal of this post is to serve as a broad overview of programming languages for beginners to get their feet wet.

Beginners often wonder which programming language they should learn first. While there are some choices that are objectively better than others, any general purpose programming language will have concepts applicable to other languages. Having a solid grasp of those fundamentals will be very helpful in any programmer’s journey.

We’ll be covering three sub-topics in this overview programming languages: generations of programming languages, paradigms of programming languages, and execution types of programming languages.

Generations of Programming Languages

As more great minds entered the fields of engineering and technology, they developed more advanced programming languages. With today’s modern programming languages, powerful capabilities can be unleashed with just a few text commands.

However, this wasn’t always the case. Modern programming languages have evolved from their earlier predecessors which were much more difficult to use and understand. Let’s discuss them one by one.

Machine Language (1st Generation)

Computers can only read one language: machine language. This is true even today when using modern programming languages. The difference is that modern programming languages provide extremely useful abstractions that prevent us from having to write machine language.

Machine Language
Machine Language

Machine language is represented in binary, or in other words, ones and zeros. We touched on this topic a bit in my post about basic computer literacy. Fortunately, we rarely have to deal directly with machine language these days. We are standing on the shoulders of giants.

Assembly Language (2nd Generation)

Next came assembly language, which is a huge step up from machine language. Instead of writing ones and zeros, we have the luxury of using text to tell the computer what to do. This allows us to give instructions in a way that is much more natural for human brains, and let a program called an assembler translate the instructions into machine language.

Assembly Language
Assembly Language

Unfortunately, we are still limited by the fact that in assembly language, one assembly code instruction translates to one machine instruction. This is makes for tedious work, despite the obvious advantages over machine language.

Unlike machine language, assembly language is still used directly today. Low-level embedded systems, device drivers, and real-time systems are often programmed in assembly language. Assembly language gives the programmer greater direct control over the machine instructions, which can be useful when optimizing for performance or working with hardware.

Structured Programming Language / High-Level Language (3rd Generation)

Eventually, people started creating higher-level languages. These people saw the ideas of assembly language and took them one step further. These high-level programming languages still use words instead of binary numbers, but one high-level instruction may translate into many machine instructions. Structured programming concepts are built into these languages by default.

Java, a structured, high-level programming language.
Java, a structured, high-level programming language.

This all provides a huge boost to programmer productivity, as it allows the programmers to focus more on what they want the computer to do, and not on how the computer performs the task. These languages are much more beginner friendly than assembly language.

A computer cannot execute high-level code directly. Instead, we must compile or interpret the code. More on that in a moment.

Most of the popular and recognizable programming languages in use today fall into this category. This includes languages like C, C++, C#, Java, Go, Ruby, JavaScript, and many more.

Domain Specific Programming Language (4th Generation)

Finally, we have domain specific programming languages. A domain specific programming language is a high-level language created specifically for solving a certain kind of problem.

A couple of examples include CSS and SQL. We use CSS specifically for adding style to web pages, and we use SQL specifically for interacting with databases.

SQL, a domain specific programming language
SQL, a domain specific programming language

Another example would be JSON, which is just a subset of JavaScript that’s commonly used for sending object data over the internet via HTTP.

These languages make it very easy to solve problems within their domain, but they are not very useful for solving problems outside of their domain.

Complex software, like web applications, often use a mix of both high-level languages and domain specific languages to solve problems.

Now let’s move on to our second topic: paradigms of programming languages.

Paradigms of Programming Languages

There are many different high-level programming languages, and each one has its own unique flavor. There are several different programming paradigms that languages can use. Procedural, object oriented, and functional are three of the most popular paradigms.

While we can neatly define these paradigms, the programming languages themselves often borrow ideas from all of them.

For example, while Java was clearly designed as an object oriented programming language, recent versions contain more functional concepts, like lambda expressions. It’s beneficial to become familiar with many programming paradigms in order to become a well rounded developer.

Procedural

This is the traditional method of programming, and is conceptually the most straightforward. It simply involves giving a sequence of instructions to solve a particular problem. The programmer places his/her focus on the algorithm itself. A few examples of programming languages that lean heavily on this paradigm include COBOL, Pascal, and C.

Object Oriented

In the object oriented paradigm, we organize our code into “objects”. An object is basically data and tasks you can perform with that data. We write programs in terms of how the different objects interact with each other.

This is a powerful paradigm because it allows us to model the real world and break up large problems into smaller, encapsulated problems.

Object oriented programming concepts
Concepts of object oriented programming (OOP). You could spend a long time studying this subject alone.

Much of programming involves creating abstractions that make our lives easier, and object oriented programming assists in that regard. A few examples of programming languages that lean heavily on this paradigm include Java, C#, and C++.

Functional

The functional paradigm is a declarative style of programming that treats computation as the evaluation of mathematical functions. It avoids changing state and mutable data. I have to admit, I’m much less adept with functional programming than the other two paradigms.

While academia tends to get excited about functional programming, object oriented programming is much more common in the business world.

However, functional programming has many advantages and can be an extremely powerful tool in the right hands. It often makes programs less complex and easier to reason about.

Languages often borrow from functional concepts without forcing you to embrace pure functional programming in its entirety. The idea of “passing a function to a function” alone is a great tool to have on your tool belt.

A few examples of programming languages that lean heavily on this paradigm include Haskell, Lisp, and Erlang. I’d love to hear about your experiences with functional programming in the comments, especially if you have any tips for helping others think in that paradigm.

With that section wrapped up, let’s move on to our final topic: execution types of programming languages.

Execution Types of Programming Languages

There are three main execution types of programming languages. A program can be compiled, interpreted, or ran on a virtual machine.

Compiled Languages

In compiled languages, a program called a compiler creates an executable file that runs directly on the machine. This executable contains machine code, so the original source code is no longer necessary once the executable has been created. Because of this, compiled programs usually run pretty fast. An example of a compiled language is C or C++.

Interpreted Languages

In interpreted languages, a program called an interpreter reads the code, follows along, and does what it says. We need the source code every time the program is ran, and we don’t create an executable.

Interpreted programs are usually slower than compiled programs. JavaScript, the language I’ve been using recently in my game tutorials, is an example of an interpreted language.

Virtual Machine

A language designed for a virtual machine is like a cross between a compiled and interpreted language. We compile the program, but into something called “byte code”, not machine code. The virtual machine then acts as the interpreter for the byte code.

These programs are usually slower than machine code, but faster than interpreted programs.

A couple of examples of languages that run on a virtual machine include Java and C#. In Java, the virtual machine is called the JVM (Java Virtual Machine). In C#, the virtual machine is called the CLR (Common Language Runtime).

Summary

As a beginner, the sheer number of programming languages out there can be overwhelming. It can make it difficult to know where to begin learning.

Fortunately, there are some ways of categorizing programming languages that allow us to move past all the cruft and focus on the fundamentals.

As years have gone by programming languages have become faster, easier to work with, and more powerful. Yet COBOL, an unfashionable language which first appeared in 1959, still accounts for more than 70 percent of the business transactions that take place in the world today.

This just goes to show that the business world prizes working software above all else, and a professional programmer is likely to encounter all different kinds of programming languages throughout his/her career. It helps to understand how these different languages have evolved and what capabilities they offer. Doing so will prepare you to learn whatever hot new language comes along next.

Thanks for reading as always, and don’t forget to subscribe!