Press Start
So you want to learn to program? You’ve made a good decision. Programming is a fantastic skill to learn, and it’s great fun. It can be used to build the next generation of apps, hack a Raspberry Pi or Arduino, write the latest blockbuster games—and a ton of other things. In fact, once you learn how to program, the only limit is your imagination.
In this chapter, we’ll briefly survey the history of programming, look into what a computer program actually is, and then introduce the JavaScript programming language, which we’ll be using to learn how to program.
We’ll also be jumping right in and getting started with some programming, writing not one, but two programs in JavaScript!
Here’s what this chapter will cover:
- what programming actually is
- algorithms and pseudocode
- a brief history of programming
- an introduction to the JavaScript language
- “Hello, World!”—your first JavaScript program
- JavaScript in the web browser
- “I Can Code a Rainbow”—your second JavaScript program
- the mindset of a programmer
We’ll also finish the chapter with some programming challenges to help you to test your newfound skills—as we’ll do at the end of every chapter in this book.
Programming
Programming is about making computers do what you want them to do. A computer program is basically a series of instructions that tell your computer how to perform a task. Unfortunately, computers don’t speak the same language as us.
For example, you can’t just write “change the color of the circle to blue” and expect the computer to understand. A programming language acts as an intermediary: it’s a language that can be understood by both computers and humans.
Learning to program is a bit like learning a foreign language, except computers can be very picky about grammar (even more so than my French teacher was!). You need to make sure you get everything in the right place, and the syntax needs to be just right. Computers are powerful, and you can get them to do some truly impressive stuff, but they’ll also fall to pieces if just one bracket is out of place!
Writing a program is basically just writing a set of instructions for a computer to follow. The problem is, they have to be very precise instructions. Any slight ambiguity, and the computer will do something completely different from what you had in mind—or it might even crash.
Algorithms
The word algorithm is used quite frequently these days. You might have heard of the “Instagram algorithm” or the “Google search algorithm”. But what exactly is an algorithm? The word “algorithm” is a Latinization of the name of a Persian mathematician, Al-Khwarizmi, who wrote the first algebraic textbook and liked to explain his methods using a step-by-step approach.
This led to the word algorithm being used to describe any step-by-step method. It should be clear what to do at each step and what each step does. For example, here’s an algorithm for making a cup of tea:
- Boil water in a kettle.
- Get a cup.
- Get a teabag.
- Put the teabag in the cup.
- When the kettle has boiled, pour the water into the cup.
- Leave it to brew for two minutes.
- Take the teabag out of the cup.
- Get milk.
- Add milk to the tea.
- Stir the tea.
Milk after Tea
I realize my instruction to add milk after the tea is made might be controversial. If you think milk should be added first, I’m sorry, but you’ll just have to accept that you’re wrong on this one.
Those instructions seem fairly basic and straightforward, but there are quite a few assumptions made, and some steps are a bit ambiguous. How do you boil a kettle? Where do you get the cup and teabag from? How much water should I pour into the cup? These questions are left unanswered. This is usually okay, as most people are familiar with the process of making tea, but someone who had never seen a cup of tea being made might struggle to follow some of the steps (although I accept that it might be very hard to find such a person).
Pseudocode
Pseudocode is pretend code you can write to illustrate what a program does without having to worry about the complexities of an actual programming language. It still follows the conventions and structure of a program and uses precise commands, but without the specifics of a language.
For example, the instruction “display a message on the screen” might be written in pseudocode as display(message)
, whereas in the Python programming language it would be written as print(message)
. Notice that the Python code uses the very specific notation of print
, which is the command it uses to display messages on the screen. Other languages use different commands to basically do the same thing.
The example of making a cup of tea could be written in pseudocode like so:
boil(water,250ml) in kettleget(cup) from cupboardget(teabag) from boxput(teabag) in cupwhen(kettle boils) { pour(water, 250ml) in cup }wait(2 mins)remove(teabag) from cupget(milk, 20ml)add(milk, 20 ml) to teastir(tea)
A programmer who knows a how to program in a specific language should be able to follow a pseudocode example and then write it in their language of choice. Pseudocode is useful for planning out a program before you start coding, and it also makes it easier to share ideas between programmers who use different programming languages.
A Brief History of Programming
The earliest computers were programmed using punched cards to represent a binary number system, the number system that computers use. The binary system is made up entirely of 1s and 0s that loosely translate to “on” and “off”. On the cards, a hole represented 1
and no hole 0
. After this, people started to develop languages that could be used to “speak” to the computer.
The first computer programs were written in machine code and assembly language. These are low-level programming languages that are closely associated with a computer’s hardware. This means they can be difficult languages to program in because they involve writing abstract code that’s heavily tied to a computer’s architecture. In fact, it’s rare to find anyone who programs in machine code or assembly nowadays, but those who do will work closely with a computer’s hardware—for example, writing device drivers, or working on embedded systems.
High-level programming languages use abstractions that make the code easier for humans to read and write. Programs are written in a language such as Swift, C# or Java, which is then compiled into machine code and executed. The programs written using these languages are very fast, making high-level languages suited to writing games and professional business software where speed is important.
Scripting languages are another type of high-level language, but they’re interpreted, instead of compiled, which means that they’re translated into machine code when the program runs, rather than beforehand. This means that they’re often slower than compiled languages, although interpreters are becoming more sophisticated, making some interpreted languages almost as fast as compiled languages. Some common scripting languages that you might hear about are Python, Ruby and, of course, JavaScript.
JavaScript
The language we’ll be learning in this book is JavaScript, often referred to as the language of the Web. Pretty much every web browser can run JavaScript, making it one of the most popular programming languages in the world.
JavaScript is a great language to use when learning how to program. It has a low barrier to entry: all you need to be able to program in JavaScript is a web browser. It’s easy to get started, and the basics are easy to pick up. It’s also a flexible and expressive language that can create a variety of powerful programs.
JavaScript is a scripting language that’s interpreted and compiled at runtime. This means that it requires an engine to interpret and run a program. This is usually done by a web browser, but there are JavaScript engines that can run programs without a browser. JavaScript is also a dynamic language, which means that elements of a program can change while it’s running, unlike a compiled language such as C++.
The History of JavaScript
The World Wide Web started life as a bunch of pages linked by hyperlinks. Users soon wanted more interaction with these pages, so Netscape (an early browser vendor) asked one of their employees, Brendan Eich, to develop a new language for their Navigator browser. He came up with a prototype scripting language called Mocha in just ten days. The new language was renamed LiveScript, but was then hastily rebranded as JavaScript so that it could benefit from the publicity that Sun Microsystems’ Java language was attracting at the time.
The name “JavaScript” has often caused some unfortunate confusion, with JavaScript often thought of as “Java lite”, even though the two languages are completely unrelated.
JavaScript made its debut in 1995 and ushered in an exciting new era of being able to program a web browser to do stuff. (Unfortunately, in the early days, the most common use was to create pop-up ads and spinning logos!)
By 2005, sites such as Google Maps and Gmail started to appear, and they demonstrated that JavaScript was capable of creating rich internet applications that looked and behaved like native desktop applications. This progress has continued at pace, and almost every website today will use JavaScript in some way. JavaScript has also found its way into a variety of other things such as smartphone apps, wearables and databases.
JavaScript Versions
In 1996, a decision was made to standardize JavaScript with the help of the European Computer Manufacturers Association, who would host the standard. This standardized language was called ECMAScript to avoid infringing on the “Java” trademark. This caused even more name-based confusion, but eventually ECMAScript was used to refer to the specification, and JavaScript was used to refer to the language itself. This is still the case, although there’s constant debate about changing the name. One suggestion is to officially rename JavaScript just as “JS”—which it is often called anyway (just as Michael Jordan is often referred to as “MJ”).
When JavaScript was standardized in 1997, the specification was known as ECMAScript version 1. In 2015, it was decided to publish a new specification every year, with the version named after the year it was published. As a result of this change, ECMAScript version 6 was renamed ES2015 when it was published, and since then there’s been a new version of JavaScript every year. In this book, we’ll use the most up-to-date version of JavaScript, but it’s always worth keeping up to date with the latest additions and changes to the language each year.
Backward Compatibility
An important concept in the development of the JavaScript language is that of backward compatibility. This means that all old code must work the same way when interpreted by an engine running a new specification. (It’s a bit like saying that a PlayStation 5 must still be able to run any games created for all the previous PlayStations). This is to prevent JavaScript from “breaking the Web” by making drastic changes that would mean old, legacy code used on some websites might not run as expected in modern browsers.
In this book, we’ll assume you’re using a modern browser that’s capable of running the latest version of JS. (Try to update to the latest version of whichever is your favorite browser.)
That’s enough talk about JavaScript. Let’s write your first program!
Hello, World! Your First JavaScript Program
It’s a tradition when learning programming languages to start with a Hello, World! program. This is a simple program that outputs the phrase “Hello, World!” to announce your arrival to the world of programming.
We’re going to stick to this tradition and write a Hello, World! program in JavaScript. It will be a single statement that logs the phrase “Hello, World!” to the console.
The Console?
A console is basically a command prompt used to run code. You can enter a snippet of code and it will be evaluated and the output logged to the screen. A console is a great way to test and experiment with code. You can get JS consoles to run in your computer terminal as well as JS console apps for smartphones and tablets. There are also many websites that run a console in the browser, and most browsers also have a built-in console as well.
In this book, we’ll mostly use the online jsconsole.com as our console. I’d recommend that you use it to try running the code snippets that appear throughout this book to get a feel for how they work. It’s always better to get a feel for typing in the code rather than just reading it. And it also means you can experiment with the code by making changes and checking the results.
Another option for a console is to use the one built into your browser. To open it, simply follow the instructions below, depending on your browser:
- Firefox: hold
Shift
+Ctrl
+J
(orOption
+⌘
+J
on a Mac) or pressF12
- Safari: hold
Option
+⌘
+C
(note that you need to enable the Developer Menu in preferences first) - Chrome: hold
Shift
+Ctrl
+J
(orOption
+⌘
+J
on a Mac) or pressF12
- Edge/Internet Explorer: press
F12
Once you open the console in your browser, it will act exactly the same as jsconsole.com. The image below shows Chrome’s built-in console.
Okay, let’s write our first program. Go to jsconsole.com or open up your browser’s console and type the following code, then press the Enter
key:
console.log('Hello, World!');
Enter? Return?
I told you to press the Enter key on your keyboard above. Just to be clear, on most PC keyboards you’ll see an Enter key towards the right-hand side. (Sometimes it will just be an arrow symbol: ↵.) On Mac keyboards you’ll mostly see a return key instead. For simplicity, I’ll just refer to it as Enter from here on.
If everything went to plan, you should see “Hello, World!” displayed on the screen—just as in the screenshot below.
Congratulations! You’ve just written your first JavaScript program! It might not look like much, but a wise person once said that every programmer’s journey begins with a single line of code—or something like that, anyway!
JavaScript in the Browser
I said earlier that JavaScript is an interpreted language and needs a host environment to run. Because of its origins, the main environment that JavaScript runs in is the browser, although it can be run in other environments as well.
By far the most common use of JavaScript is still to make web pages interactive. Because of this, we should have a look at what makes up a web page before we go any further.
The Structure of a Web Page
Nearly all web pages are made up of three key ingredients: HTML, CSS, and JavaScript. HTML is used to mark up the content of the page, CSS is the presentation layer that dictates what the page will look like, and JavaScript adds the interactivity that makes the page do stuff. Together, these three technologies are known as the three layers of the Web. It’s possible to add CSS and JavaScript in HTML, but it’s good practice to keep the code for each layer separate.
We won’t be focusing on the HTML and CSS parts of a web page in this book, as we’re here to learn how to program. Some HTML and CSS will occasionally be required, though, to provide the graphical elements that our programs will need to interact with.
To save you spending a long time setting up and coding web pages, we’ll be using the CodePen website for many of the examples in this book. This site sets everything up for you so that you only need to add any HTML, CSS and JS code to create a functioning web page. It also keeps the three layers of the Web separate in three sections at the top of the editor, as you can see in the screenshot below.
CodePen also offers a console. At various points throughout this book, you’ll find it convenient to enter JavaScript code in the JS section of CodePen and then see how that code performs behind the scenes by opening the CodePen console. You can access it by clicking the Console tab at the bottom left of the CodePen interface.
Online Editors and Working Offline
There are many other options for running JavaScript code alongside HTML and CSS. Just search for “online JavaScript editor” to see more online options. It’s also possible to work offline (that is, just on your computer) by writing the code in a text editor and opening it up in a browser. See “ HTML5 Template: A Basic Boilerplate for Any Project ” for instructions on how to set this up.
Let’s try writing our second program.
I Can Code a Rainbow: Your Second JavaScript Program
We’re going to finish this chapter with a second JavaScript program that will run in the browser. This example is much more complicated than the previous one and includes a lot of concepts that will be covered in more depth in later chapters, so don’t worry if you don’t fully understand everything that’s going on at this stage! The idea is to show you what JavaScript is capable of doing and interactively introduce some of the important concepts that will be covered in the upcoming chapters.
Head over to the CodePen website and start a new Pen.
Add the following to the HTML section:
<button id='button'>click me</button>
This will display a button with an ID of button
. The ID attribute is a useful way for our JavaScript program to identify, and manipulate, certain elements on the page. It should look similar to the one in the image below.
The actual JavaScript code goes in the JS section. Add the following lines of code:
const button = document.getElementById('button');
const colors = ['red','orange','yellow','green','blue','rebeccapurple','violet'];
function change() { document.body.style.background = colors[Math.floor(7*Math.random())];}
button.addEventListener('click', change);
The first line of our program creates a variable called button
. (We cover variables in Chapter 2.)
We then use the document.getElementById
function to find the HTML element with the ID of button
. This is the button element we created in the HTML section. This is assigned to the variable button
, so from now on, whenever we refer to button
, the program knows we’re talking about that button. (Finding HTML elements is covered in Chapter 10.)
We now create another variable called colors
that’s assigned to an array containing a list of strings that represent different colors of the rainbow. (We cover strings in Chapter 3 and arrays in Chapter 5.)
Then we create a function called change
. (We cover functions in Chapter 8.) This sets the background color of the web page’s body element to one of the colors in the colors
array. (Changing the look of a page is covered in Chapter 10.)
The change
function also uses a random number to pick a color at random from the array. (Numbers, including generating random numbers, are covered in Chapter 4.)
The program ends with an event handler, which listens out for when the button is clicked. When this happens, it runs the function we just defined. (Events and how to handle them are covered in Chapter 11.)
Try clicking on the button a few times. If everything’s working correctly, the background should change to every color of the rainbow!
You can see my code on CodePen:
Rebecca Purple
rebeccapurple
is the official name for the color with a hex code of #663399
. It’s named after the daughter of the web designer Eric Meyer, who tragically died, aged just six years old. This was her favorite color and it was added to the official list of CSS colors as a tribute to her.
A Programmer’s Mindset
Before we finish the chapter, we need to have a word about programming style. Obviously the point of writing a computer program is to make it do what it’s supposed to do, but the style of the program is also important. Your code should be clear and concise, and also be consistent in the way it follows conventions—from the names you choose for variables to the amount of whitespace you leave between blocks of code. Your code should also be easy to read and include comments that explain what the code does.
You should always be looking to improve your code to make it more efficient and easier to follow. This process is called refactoring, and should be done regularly so that your code stays up to date and doesn’t become stale.
An important principle in programming is the rule “Don’t Repeat Yourself”, or DRY. This means that you should always be looking to avoid repeating lots of code. Following this principle will help make your code more flexible and easier to maintain and update. (It’s always easier to change one bit of code than hundreds!) If this sounds a bit like programmers are lazy, then you’re absolutely right! A good programmer will always be looking to write code that does the job in the most efficient and elegant way possible. Less code means less chance of bugs, and it’s easier to maintain.
A good program doesn’t just appear instantly. It starts as a plan, and grows organically into its finished state. Developing a program involves a lot of problem solving, and sometimes you’ll take some wrong turns and get stuck. This is normal, and you should be prepared to make changes and adapt. A good plan and well-commented code that follows the DRY principle will stop your code becoming a complex mess that’s impossible to follow and comprehend.
Challenges
Try writing pseudocode to describe some common tasks such as brushing your teeth or riding a bike.
Write pseudocode that will find the largest number in a list of numbers.
Try logging some different messages to the console using
console.log()
. You can see my code on CodePen.Add some more colors to the array in the “I Can Code a Rainbow” program. You can see my code on CodePen.
Summary
- An algorithm is a set of step-by-step instructions that complete a specific task.
- Pseudocode is used to write programs without using a specific programming language.
- JavaScript was created in 1995 and is considered to be the language of the Web.
- JavaScript’s main environment is the browser, but it can also run in other environments.
- Each version of JavaScript has to be backward compatible with older versions.
- Code should be easy to read and regularly refactored to keep it running smoothly.
- Remember the DRY principle when coding. Don’t Repeat Yourself!
In the next chapter, we’re going to start looking at some programming fundamentals. Let’s get going!