Learn to Code With JavaScript
By Darren Jones
()
About this ebook
A hands-on, practical Introduction to coding!
Do you want to learn to code? Perhaps you want to learn how to build the next social media sensation or blockbuster game? Or perhaps you just want to get some valuable coding experience under your belt? This easy-to-follow, practical, and fun guide is the perfect place to start on your coding journey. You'll be learning to program with JavaScript - the most popular programming language on Earth. And it runs in web browsers, making it particularly suited to creating web-based apps and games. But the principles and techniques that you'll learn will provide you with a foundation to go on and learn many other languages, too.
You'll learn:
- Programming basics, including data types, variables and more
- How to use logic to control the flow of a program
- How to use loops to repeat code over and over again
- How to write functions that can be used to store code in reusable blocks
- How to store data in collections such as arrays, sets and maps
- How to create objects that store properties and actions
- And much more!
Along the way, you'll build a collection of fun applications, including games and interactive web pages. Start learning to code today!
Darren Jones
Darren has enjoyed coding since learning how to program in BASIC on his first Acorn Electron computer. Since then, he's taught himself Ruby and JavaScript and is the author of "JavaScript: Novice to Ninja" and "Jump Start Sinatra". He also produced the "Getting Started With Ruby" video tutorials for SitePoint Premium and has written a number of articles on the SitePoint website. He was born in the city of Manchester in the UK, where he still lives, and he teaches Mathematics and Computing at a local high school.
Related to Learn to Code With JavaScript
Related ebooks
Learning Behavior-driven Development with JavaScript Rating: 5 out of 5 stars5/5Jump Start PHP Environment: Master the World's Most Popular Language Rating: 0 out of 5 stars0 ratingsJavaScript: Novice to Ninja Rating: 2 out of 5 stars2/5PHP & MySQL: Novice to Ninja Rating: 0 out of 5 stars0 ratingsCODING INTERVIEW: 50+ Tips and Tricks to Better Performance in Your Coding Interview Rating: 0 out of 5 stars0 ratingsThe Javascript Adventure Rating: 0 out of 5 stars0 ratingsCrafting HTML Email Rating: 0 out of 5 stars0 ratingsFront End A Complete Guide - 2021 Edition Rating: 5 out of 5 stars5/5Responsive Media in HTML5 Rating: 0 out of 5 stars0 ratingsMastering jQuery UI Rating: 0 out of 5 stars0 ratingsUnleashing the Power of CSS Rating: 0 out of 5 stars0 ratings10 Lessons in Front-end Rating: 2 out of 5 stars2/5jQuery Mobile Web Development Essentials - Third Edition Rating: 0 out of 5 stars0 ratingsWb Development full course : from zero to web hero Rating: 0 out of 5 stars0 ratingsIan Talks JavaScript Libraries and Frameworks A-Z: WebDevAtoZ, #4 Rating: 0 out of 5 stars0 ratingsPrinciples of Programming: Java Level 1 Rating: 0 out of 5 stars0 ratingsPHP Error Reporting: How To Do It Right Rating: 0 out of 5 stars0 ratingsHTML for the Business Developer: with JavaServer Pages, PHP, ASP.NET, CGI, and JavaScript Rating: 3 out of 5 stars3/5Introduction to PHP Rating: 3 out of 5 stars3/5Reference to PHP, Second Edition Rating: 0 out of 5 stars0 ratingsJavaScript: Best Practices to Programming Code with JavaScript Rating: 0 out of 5 stars0 ratingsSass and Compass for Designers Rating: 0 out of 5 stars0 ratingsResponsive Design High Performance Rating: 0 out of 5 stars0 ratingsYour First Week With Node.js Rating: 0 out of 5 stars0 ratingsPHP and MongoDB Web Development Beginner’s Guide Rating: 0 out of 5 stars0 ratingsPython For Beginners: The Comprehensive Guide To Learning, Understanding, And Mastering Python Programming Rating: 0 out of 5 stars0 ratingsFirst Web Dev Job - Exactly how to land one fast! Rating: 0 out of 5 stars0 ratingsCertified Web Developer: HTML, CSS and JavaScript Rating: 0 out of 5 stars0 ratings
Programming For You
Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5C Programming For Beginners: The Simple Guide to Learning C Programming Language Fast! Rating: 5 out of 5 stars5/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsCoding with JavaScript For Dummies Rating: 0 out of 5 stars0 ratingsLinux: Learn in 24 Hours Rating: 5 out of 5 stars5/5SQL All-in-One For Dummies Rating: 3 out of 5 stars3/5Beginning Programming with C++ For Dummies Rating: 4 out of 5 stars4/5HTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5Python Data Structures and Algorithms Rating: 5 out of 5 stars5/5Narrative Design for Indies: Getting Started Rating: 4 out of 5 stars4/5C All-in-One Desk Reference For Dummies Rating: 5 out of 5 stars5/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5C# 7.0 All-in-One For Dummies Rating: 0 out of 5 stars0 ratingsJavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5
Reviews for Learn to Code With JavaScript
0 ratings0 reviews
Book preview
Learn to Code With JavaScript - Darren Jones
Chapter 1: 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.
Making teaMilk 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 kettle
get(cup) from cupboard
get(teabag) from box
put(teabag) in cup
when(kettle boils)
{ pour(water, 250ml) in cup }
wait(2 mins)
remove(teabag) from cup
get(milk, 20ml)
add(milk, 20 ml) to tea
stir(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.
Google Maps showed that JavaScript could be used to create advanced web applicationsJavaScript 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 (or Option + ⌘ + J on a Mac) or press F12
Safari: hold Option + ⌘ + C (note that you need to enable the Developer Menu in preferences first)
Chrome: hold Shift + Ctrl + J (or Option + ⌘ + J on a Mac) or press F12
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.
Chrome's built-in consoleOkay, 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.
The CodePen editor separates HTML, CSS and JS into three distinct sectionsCodePen 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:
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.
Click MeThe 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