Hello, JavaScript
In this chapter, we’re going to introduce the JavaScript language, as well as set up a programming environment. We’ll also get started with some programming and write a couple of programs in JavaScript!
Here’s what this chapter will cover:
What is programming?
The history of JavaScript
The tools that are needed to program in JavaScript
Installing Node.js
JavaScript in the console
Hello, world! Your first JavaScript program
JavaScript in the web browser
Graceful degradation and progressive enhancement
A more complicated JavaScript program
Project - we'll start a quiz project that will be developed throughout the book
Programming
Programming is about making computers do what you want. A computer program is basically a series of instructions that tell your computer how to perform a task. Unfortunately, though, computers don’t speak the same language as us ― they only use 1s and 0s. The first computers were programmed using punched cards, with a hole representing a 1 and no hole representing 0.
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 is heavily tied to a computer’s architecture. If speed is very important, however, then writing in machine code or assembly language can be the best option.
High-level programming languages, on the other hand, allow abstractions to be used that make the code easier for humans to read and write. Programs are written in a language such as C, 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. Most native apps are also written in higher-level languages.
Scripting languages are also high-level, but they are interpreted, which means they are translated into machine code at run time. This often makes them slower than compiled languages, although interpreters are becoming ever more sophisticated, and increasingly blurring the lines between compiled and interpreted languages.
JavaScript
The language we’ll be learning in this book is JavaScript, often referred to as the language of the web.
Nearly all web browsers can run JavaScript, making it one of the most popular programming languages in the world. It has a low barrier to entry ― all you need to program in JavaScript is a text editor and a web browser. Although it is easy to get started, JavaScript can be a tricky language to grasp as it has some unique features and interesting quirks. Once you have mastered it, though, you’ll find it is a very flexible and expressive language that can create some powerful applications.
JavaScript is a high-level scripting language that is interpreted and compiled at run time. This means it requires an engine that's responsible for interpreting a program and running it. The most common JavaScript engines are found in browsers such as Firefox, Chrome or Safari, although JavaScript can be run without a browser using an engine such as Google V8. Many modern JavaScript engines use a Just-In-Time (JIT) interpreting process, which considerably speeds up the compilation, making programs run faster.
JavaScript is also a dynamic language, so elements of a program can change while it's running, and it can do lots of things in the background at run time (such as type checking, which we'll cover later) ― things that a compiled language like C++ would do at compile time.
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. This needed to be done quickly because of the intense competition between Netscape and Microsoft at the time.
Eich managed to create a prototype scripting language in just 10 days. To do this, he borrowed various elements from other languages, including AWK, Java, Perl, Scheme, HyperTalk and Self. This was an impressive feat, but in the rush to be first to market, a number of quirks and bugs ended up in the language that were never fully addressed.
The new language was originally called Mocha, but it was changed to LiveScript, then hastily rebranded as JavaScript so it could benefit from the publicity that Sun Microsystem’s Java language was attracting at the time. This name has often caused some confusion, with JavaScript often considered a lighter version of Java. However, the two languages are unrelated ― though JavaScript does have syntactical similarities to Java.
JavaScript made its debut in version 2 of Netscape’s Navigator browser in 1995. The following year, Microsoft reverse-engineered JavaScript to create their own version, calling it JScript to avoid copyright issues with Sun Microsystems, who owned the Java trademark. JScript shipped with version 3 of the Internet Explorer browser, and was almost identical to JavaScript ― it even included all the same bugs and quirks ― but it did have some extra Internet Explorer-only features. Microsoft included another scripting language called VBScript with Internet Explorer at the same time.
JavaScript (and JScript) was immediately popular. It had a low barrier to entry and was relatively easy to learn, which meant an explosion in its usage for making web pages dynamic and more interactive. Unfortunately, its low barrier was also a curse ― many people were now writing snippets of code without understanding what they were doing. Code could now be easily copied and pasted, and was often used incorrectly, leading to lots of poor examples appearing all over the web.
JavaScript was also frequently used to create annoying pop-up adverts, as well as for 'browser sniffing' (the process of detecting which browser was being used to view a web page). It had started to gain a negative reputation.
The Browser Wars
By the time Netscape Navigator 4 and Internet Explorer 4 were released, JavaScript had become incredibly popular. Microsoft had started a lot of hype about the term Dynamic HTML, or DHTML for short, to refer to the use of JavaScript to make HTML more interactive and dynamic. In an attempt to capitalize on this popularity, Netscape and Microsoft tried to add new proprietary features, which lead to different syntaxes being used. This 'arms race' of adding new features became known as the 'Browser Wars'. The unfortunate downside was that programmers had to write two versions of code to achieve the same results in each browser. Professional programmers often dismissed JavaScript as a toy language, unsuitable for any serious programming, but this was unfair criticism ― the language wasn’t the problem, it was the way it was being used.
Eventually, Microsoft won the browser wars and Internet Explorer emerged as the dominant browser. Support for standards also increased, helped largely by the efforts of the Web Standards Project (WaSP). Developer and browser vendors started to work together and embrace the standards laid out by the World Wide Web Consortium (W3C) and ECMA.
The open-source web browser, Firefox, debuted in 2002, and Apple launched the Safari browser in 2003. Both had strong standards support, which meant developers were able to produce better web applications using JavaScript that behaved consistently across different browsers.
Web 2.0
In 2005, sites such as Google Maps, Flickr and Gmail started to appear, and demonstrated that JavaScript was capable of creating rich internet applications that looked and behaved like native desktop applications. At around the same time, the term Ajax, short for Asynchronous JavaScript And XML, was coined by Jesse James Garrett. This described a technique of obtaining data from a server in the background and updating only the relevant parts of the web page without the need for a full page reload, enabling users to continue interacting with the rest of the page. This created a more seamless experience for users and was used extensively in many Web 2.0 applications. As a result, professional programmers started to take more notice of JavaScript, and it began to be seen as a powerful and flexible programming language, capable of producing high-quality web applications.
Standards
As JavaScript became used for more sophisticated applications, and browsers embraced standards, the JavaScript landscape changed. A new browser war started, but this time it was about which browser could be the most standards-compliant. There has also been competition to increase the speed of the JavaScript engine that is built into the different browsers. This started in 2008 when engineers at Google developed the V8 engine to run inside the Chrome browser. It was significantly faster than previous JavaScript engines, and signaled another arms race as other browser vendors responded by increasing the speed of their engines. JavaScript now runs significantly faster in modern browsers and the pace of improvement shows no sign of slowing down.
HTML5
HTML5 is the latest HTML specification, though it’s actually more of an umbrella term for all the latest technologies that are used on the web. This includes HTML, CSS3 and lots of APIs that use JavaScript to interact with web pages. These will be covered in more detail in [Chapter 10].
HTML5 was finalized in 2014, and the recommendation for the next version, 5.1, was proposed at the end of 2016 (https://www.w3.org/TR/html/). It has quickly become the dominant standard for web development. JavaScript is a key feature in how some of its more interesting aspects work.
Node.js
In 2009, Ryan Dahl developed Node.js (commonly known as just Node), which allowed server-side applications to be written in JavaScript. Node is based on Google's V8 engine and allows the creation of fast and powerful real-time web applications written exclusively in JavaScript. It also lead to many applications and JavaScript libraries that don’t use the browser at all. Node.js has proven to be exceptionally popular, and its usage continues to grow. This has increased the interest in and use of JavaScript as it starts to appear in many environments outside the web.
The popularity of Node has lead to an interesting development known as Isomorphic JavaScript. This involves having the same JavaScript code that can be run either on the client or server side: if a browser is unable to run the code, it can be run on the server and downloaded, or if the server is unavailable, the code can be run on the client.
JavaScript Versions
In 1996, Netscape and Sun Microsystems decided to standardize the language, along with the help of the European Computer Manufacturers Association, who would host the standard. This standardized language was called ECMAScript to avoid infringing on Sun’s Java trademark. This caused even more confusion, but eventually ECMAScript was used to refer to the specification, and JavaScript was (and still is) used to refer to the language itself.
In an ideal world, the ECMAScript standard should mean that all JavaScript engines interpret programs in the same way. But the specification can be difficult to interpret in places, so the implementations of JavaScript can vary from engine to engine. This is why some web browsers behave differently when running JavaScript programs. JavaScript is also a superset of ECMAScript as it often contains additional non-standard features such as the alert()
function.
The working group in charge of maintaining ECMAScript is known as Technical Committee 39, or TC-39. It’s made up of representatives from all the major browser vendors such as Apple, Google, Microsoft and Mozilla, as well as invited experts and delegates from other companies with an interest in the development of the web. They have regular meetings to decide on how the language will develop.
When JavaScript was standardized by TC-39 in 1997, the specification was known as ECMAScript version 1. Version 2 followed a year later but didn't make any major changes to the language. In 1999, ECMAScript version 3 was published in December 1999 and added a variety of new features.
The development of ECMAScript version 4 was mired by disagreements on TC-39 over the direction the language should take. Some members believed the language needed lots of big changes to make it more robust, while others thought it only needed minor changes. Many new features were proposed, but were often felt to be overly ambitious or too difficult to implement in browsers. After many years without progress, version 4 was eventually abandoned, and the working party skipped over this version and went straight on to developing version 5. It was agreed that this needed be a slimmed down specification that could actually be implemented, and it was finally published in December 2009. ECMAScript version 5 added many new features to the language, but it was far less ambitious than the ill-fated version 4. Despite this, some of these features took a long time to be fully supported by browser JavaScript engines.
After ES5 was published, work started on a new standard that was codenamed 'Harmony'. The idea with Harmony was to outline all the desirable features for the next versions of JavaScript. It would take another six years, but eventually most of these features made it into ECMAScript version 6, although some of them were put off until version 7 or later.
In 2015, TC-39 decided to adopt a new approach and start publishing a new specification every year, with the version named after the year it was published. This meant that only the features that had been approved would make it into the specification for that year. As a result, ECMAScript version 6 was renamed ECMAScript 2015 when it was published in June 2015 and it added some major new features to the language. The plan is to release a new version in June of each year so the language evolves slowly as new features are added in a more gradual way; rather than making drastic additions every five or so years. This means ES2015 will probably be the last version of JavaScript to have such a large number of new features and make significant changes to the language. In fact, version 7, or ECMAScript 2016, was published in June 2016 and only added two new features to the previous version.
In this book we’ll refer to ES2015 as ES6, as this is what it’s most commonly called. The code examples will use the most up-to-date syntax, with a note to say which version of ECMAScript introduced a particular feature.
We'll also assume you're using a modern browser (try to update to the latest version of whichever is your favorite). You can see a chart that shows which features have been implemented in different browsers here.
The Future of JavaScript
These are exciting times for JavaScript as it’s used for more and more applications beyond simply making web pages interactive. There’s been a huge rise in the use of Single Page Applications (SPAs), which run in the browser and rely heavily on JavaScript. The next iteration of these are Progressive Web Apps (PWAs) that use web technologies to create applications that behave like a native app on a mobile device, but without being installed from an app store. HTML5 games that use JavaScript extensively are also becoming increasingly popular, especially as the graphical ability of browsers continues to improve.
JavaScript and HTML5 technologies can be used to develop browser extensions, Windows desktop widgets and Chrome OS applications. Many non-web-related applications also use JavaScript as their scripting language. It can be used to add interactivity to PDF documents, interact with a database, and even control household appliances!
It certainly seems like JavaScript has a bright future. There are many more exciting new features under discussion that will hopefully make it into future versions of JavaScript and help to make it a more powerful and expressive language. As the web platform continues to evolve and mature, and its usage grows beyond the browser, JavaScript is sure to remain a central part of future developments in technology.
A Ninja Programming Environment
If you're going to be a JavaScript programmer, you're going to need some tools. It is possible to write and run JavaScript programs using just a browser, but in order to get the most out of this book, you'll need a text editor for writing and editing your programs and a JavaScript engine to run them in. This means you'll need a modern, an up-to-date browser, and an installation of the latest version of Node.
I was a little apprehensive about suggesting that Node be installed at the start of the book when we are still covering the basics of learning JavaScript. But after a lot of consideration, I think it’s the best thing to do for the following reasons:
- A lot of online tutorials require you to have Node installed. I don't think I'll be doing you any favors by leaving you unable to follow these tutorials without a Node installation.
- Node allows you to use most of the latest features in the language, whereas some of them won't work in browsers.
- You'll be able to install a huge variety of tools and code libraries using npm (The Node Package Manager), which is currently the largest code repository in the world.
- Node can be used to install Babel, a transpiler that will convert code written in the latest version of JavaScript into code that can will run in most browsers.
If you don't want to install Node at this point (or you are unable to, for whatever reason), then it will still be possible to run most of the code examples in the book. There are also a number of online options that will let you use the latest version of JavaScript.
Installing Node
There are two options for installing Node: The installer or Node Version Manager.
Node Installer
If you use Windows or Mac OS, then you can use the Node Installer to do all the installation for you ― all you need to do is download it and follow the instructions.
Node Version Manager
The other option is to use the Node Version Manager (nvm). An advantage of using nvm is that it allows you to install multiple versions of Node and makes it easy to quickly update your installation to the latest version. Unfortunately, nvm doesn’t support Windows, but can be installed on a Mac or Linux. To download and install nvm, just follow the two-step process outlined below:
The Command Line
If you're not familiar with running apps and tools from the command line, then don't worry, it's not that difficult. It might seem strange at first, but after a while, you'll soon be wondering how you coped without it!
You can find this on Mac OS in Applications -> Utilities -> Terminal, or use Spotlight to search for Terminal. Type the command into this window and hit Return to run it.
On Windows, you access it by entering cmd in the Start menu.
If you're using Linux, I assume you're already comfortable with opening and using the command line!
Step 1: Install Build Tools
If you have a Mac, you’ll need to install the Xcode command line tools by running the following command:
xcode-select --install
If you’re using Linux, you'll need to install the “build-essential” package. This can be done by running the following commands on Debian-based distros (use your package manager of choice with other distros):
sudo apt-get updatesudo apt-get install build-essential
Step 2: Install nvm
To install nvm, simply run the following command:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash
Now that nvm is installed, you'll need to reload your shell, before you can install Node. This can be done using the following command in Mac Os:
. ~/.bash_profile
Or by using the following command in Linux:
. ~/.bashrc
Now you can install the latest version of Node with the following command:
nvm install node
You might have to wait a while for everything to download and install, but once it's finished, you can check everything is working properly by entering the following command:
node -v
This returns the version number of Node that is installed.
You can use nvm to install multiple different versions of Node, as well as using it to switch from one version to the other. You can find out more about it by reading this article https://www.sitepoint.com/quick-tip-multiple-versions-node-nvm/.
JavaScript In The Console
A console is a useful tool for experimenting and testing out pieces of code. It allows you to enter code, then it displays the output after you press 'Enter'. This is different from a full JavaScript program that contains many lines of code that are interpreted at the same time. A console lets you see the results of each line of code as it is entered and is perfect for trying out small snippets of code. We'll often use the console to demonstrate many of the examples in this book.
There are three options available to use a console:
- If you installed Node, you can use the REPL, which stands for Read Eval Print Loop. It allows you to write JavaScript in the console then outputs the results. To start the REPL, all you need to do is open up a terminal prompt and enter the following command:
node
This should then display a prompt like the one shown in the screenshot below:
To exit the REPL, simply hold the ctrl key and hit C twice.
- Another option is to use the JavaScript console that comes with your browser. You can access the console by opening your browser and pressing F12 (or Command + Option + I on a Mac) to open the developer tools then clicking on the Console tab. It should look similar to the screenshot below:
- The last option is to use the E66 Console website. This allows you to enter JavaScript commands directly into the browser and see the results. It also lets you write in ES6 and see what it looks like after it has been transpiled into ES5.
Text Editors
One of the best things about programming in JavaScript is that you don't need any fancy and expensive programs to write the code – just a simple text editor.
The default text editor that comes with your operating system (such as Notepad on Windows) will work just fine, although you might want to upgrade to a text editor that is geared towards programming. These offer extra features such as code highlighting, code completion and file browsing without using too much of your system's resources. There are a number of good free options available, including Atom text editor and Brackets (which is actually built using JavaScript!).
Another option is to use an Integrated Development Environment (IDE). These usually have more features than text editors, but they could be considered overkill for small projects. The community edition of Microsoft Visual Studio is a good option that is also free to use.
Online Options
CodePen, JSFiddle and JS Bin are all online services that let you enter HTML, CSS and JavaScript code and view the results. They even allow you to use pre-processors on your JavaScript and CSS. This means you can write your code using the most up-to-date version of JavaScript and it will still work, even if your browser doesn't support it. They also let you save all your creations in the cloud.
Many of the examples in this book have been saved on CodePen, so you can take a look at the code as well as saving your own copy to play around with.
Your First JavaScript Program
That’s enough talk about JavaScript! Let's write your first program.
It is 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.
To get started, you'll need to open up your preferred console (either the Node REPL, browser console, or ES6 Console on the web). Once the console has opened, all you need to do is enter the following code:
console.log('Hello world!');
Then press Enter. if all went to plan you should see an output of ‘Hello world!’ displayed; similar to 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 ninja programmer’s journey begins with a single line of code (or something like that, anyway!).
JavaScript in the Browser
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; for example, our first program that we just wrote ran in the Node REPL. Node can also be used to run JavaScript on a server. 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.
Three Layers of the Web
Nearly all web pages are made up of three key ingredients ― HTML, CSS and JavaScript. HTML is used to mark up the content. CSS is the presentation layer, and JavaScript adds the interactivity.
Each layer builds on the last. A web page should be able to function with just the HTML layer ― in fact, many websites celebrate ' naked day ' when they remove the CSS layer from their site. A website using just the HTML layer will be in its purest form and look very old school, but should still be fully functional.
Keep These Layers Separate
It is widely considered best practice to separate the concerns of each layer, so each layer is only responsible for one thing. Putting them altogether can lead to very complicated pages where all of the code is mixed up together in one file, causing ‘tag soup’ or 'code spaghetti'. This used to be the standard way of producing a website and there are still plenty of examples on the web that do this.
Unobtrusive JavaScript
When JavaScript was initially used, it was designed to be inserted directly into the HTML code, as can be seen in this example that will display a message when a button is clicked:
<button id='button' href='#' onclick='alert("Hello World")'>Click Me</a>
This made it difficult to see what was happening, as the JavaScript code was mixed up with the HTML. It also meant the code was tightly coupled to the HTML, so any changes in the HTML required the JavaScript code to also be changed to stop it breaking.
It’s possible to keep the JavaScript code away from the rest of the HTML by placing it inside its own <script>
tags. The following code will achieve the same result as that above:
<script>const btn = document.getElementById(’link’)btn.addEventListener('click', function() { alert('Hello World!');};</script>
This is better because all the JavaScript is in one place, between the two script tags, instead of mixed with the HTML tags.
We can go one step further and keep the JavaScript code completely separate from the HTML and CSS in its own file. This can be linked to using the src
attribute in the script
tag to specify the file to link to:
<script src='main.js'></script>
The JavaScript code would then be placed in a file called main.js
inside the same directory as the HTML document. This concept of keeping the JavaScript code completely separate is one of the core principles of unobtrusive JavaScript.
In a similar way, the CSS should also be kept in a separate file, so the only code in a web page is the actual HTML with links to the CSS and JavaScript files. This is generally considered best practice and is the approach we’ll be using in the book.
Self-Closing Tags
If you’ve used XML or XHTML, you might have come across self-closing tags such as this script tag:
<script src='main.js' />
These will fail to work in HTML5, so should be avoided.
You may see some legacy code that uses the language attribute:
<script src='main.js' language='javascript'></script>
This is unnecessary in HTML5, but it will still work.
Graceful Degradation and Progressive Enhancement
Graceful degradation is the process of building a website so it works best in a modern browser that uses JavaScript, but still works to a reasonable standard in older browsers, or if JavaScript or some of its features are unavailable. An example of this are programs that are broadcast in high definition (HD) ― they work best on HD televisions but still work on a standard TV; it’s just the picture will be of a lesser quality. The programs will even work on a black-and-white television.
Progressive enhancement is the process of building a web page from the ground up with a base level of functionality, then adding extra enhancements if they are available in the browser. This should feel natural if you follow the principle of three layers, with the JavaScript layer enhancing the web page rather than being an essential element that the page cannot exist without. An example might be the phone companies who offer a basic level of phone calls, but provide extra services such as call-waiting and caller ID if your telephone supports it.
Whenever you add JavaScript to a web page, you should always think about the approach you want to take. Do you want to start with lots of amazing effects that push the boundaries, then make sure the experience degrades gracefully for those who might not have the latest and greatest browsers? Or do you want to start off building a functional website that works across most browsers, then enhance the experience using JavaScript? The two approaches are similar, but subtly different. This blog post might help you to decide which approach to take.
Your Second JavaScript Program
We’re going to finish the chapter with a second JavaScript program that will run in the browser. This example is more complicated than the previous one and includes a lot of concepts that will be covered in later chapters in more depth, so don’t worry if you don't understand everything at this stage! The idea is to show you what JavaScript is capable of, and introduce some of the important concepts that will be covered in the upcoming chapters.
We’ll follow the practice of unobtrusive JavaScript mentioned earlier and keep our JavaScript code in a separate file. Start by creating a folder called rainbow
. Inside that folder create a file called rainbow.html
and another called main.js
.
Let’s start with the HTML. Open up rainbow.html
and enter the following code:
<head><meta charset='utf-8'><title>I Can Click A Rainbow</title></head><body> <button id='button'>click me</button> <script src='main.js'></script></body></html>
This file is a fairly standard HTML5 page that contains a button with an ID of button
. The ID attribute is very useful for JavaScript to use as a hook to access different elements of the page. At the bottom is a script
tag that links to our JavaScript file.
Now for the JavaScript. Open up main.js
and enter the following code:
const btn = document.getElementById('button');
const rainbow = ['red','orange','yellow','green','blue','rebeccapurple','violet'];
function change() { document.body.style.background = rainbow[Math.floor(7*Math.random())];}btn.addEventListener('click', change);
Our first task in the JavaScript code is to create a variable called btn
(we cover variables in Chapter 2).
We then use the document.getElementById
function to find the HTML element with the ID of btn
(Finding HTML elements is covered in Chapter 6). This is then assigned to the btn
variable.
We now create another variable called rainbow
. An array containing a list of strings of different colors is then assigned to the rainbow
variable (we cover strings and variables in Chapter 2 and arrays in Chapter 3).
Then we create a function called change
(we cover functions in Chapter 4). This sets the background color of the body element to one of the colors of the rainbow (changing the style of a page will be covered in Chapter 6). This involves selecting a random number using the built-in Math
object (covered in Chapter 5) and selecting the corresponding color from the rainbow
array.
Last of all, we create an event handler, which checks for when the button is clicked on. When this happens it calls the change
function that we just defined (event handlers are covered in Chapter 7).
Open rainbow.html
in your favorite browser and try clicking on the button a few times. If everything is working correctly, the background should change to every color of the rainbow, such as in the screenshot below.
If you want to try this out quickly, you can checkout the code on CodePen. For the sake of getting some practice in though, I would recommend you also take the time to create these files, write up the code by hand and try running it in your browser as well. rebeccapurple
(is the official name for the color with a hex code of) #663399
. (It is named after web designer Eric Meyer’s daughter, 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.)
Don't Break the Web
An important concept in the development of the JavaScript language is that it has to be backward compatible. That is, all old code must work the same way when interpreted by an engine running a new specification (it's a bit like saying that PlayStation 4 must still be able to run games created for PlayStation 1, 2 and 3). This is to prevent JavaScript from 'breaking the web' by making drastic changes that would mean legacy code on some websites not running as expected in modern browsers.
So new versions of JavaScript can't do anything that isn't already possible in previous versions of the language. All that changes is the notation used to implement a particular feature to make it easier to write. This is known as syntactic sugar, as it allows an existing piece of code to be written in a nicer and more succinct way.
The fact that all versions of JavaScript are backwardly compatible means that we can use transpilers to convert code from one version of JavaScript into another. For example, you could write your code using the most up-to-date version of JavaScript and then transpile it into version 5 code, which would work in virtually any browser.
A new version of ECMAScript every year means it’s likely that browsers will always be slightly when it comes to implementing the latest features (they're getting faster at doing this, but it’s still taken two years for most browsers to support ES6 modules). This means that if you want to use the most up-to-date coding techniques, you'll probably have to rely on using a transpiler, such as Babel, at some point.
If you find that some code isn't working in your browser, you can add the following link into your HTML document:
<script src='https://unpkg.com/babel-standalone@6/babel.min.js'></script>
Note that this link needs to go before any JavaScript that needs to be transpiled.
You also have to change the type
attribute to 'text/babel' in any links to JavaScript files. For example, the link to the JavaScript file in the example above would change to:
<script type='text/babel' src='main.js'></script>
This isn't the best long-term solution as it requires the browser to transpile all the code at run-time, although it’s fine for experimenting with code. A better solution is to transpile your code as part of a build process, which is covered in Chapter 15.
A number of online editors such as CodePen, Babel REPL and JS Fiddle allow you to transpile code in the browser.
The ECMAScript 6 compatibility table also contains up-to-date information about which features have been implemented in various transpilers.
The Project: Quiz Ninja
Throughout this book we will be building an example application called 'Quiz Ninja'. This is a quiz application where the aim is for the player to answer questions about the real names of super heroes. The quiz application will run in the browser and use many of the concepts covered in the book. At the end of each chapter we’ll use the skills we have covered in that chapter to develop the application further.
The application will adhere to the principles of three separate web layers and unobtrusive JavaScript. So we need to keep the HTML, CSS and JavaScript in separate files. Let’s create those files now.
Create a folder called quiz
, and inside that create the following files:
index.html
main.js
styles.css
Add the following code to index.html
:
<!doctype html><html lang='en'><head><meta charset='utf-8'><meta name='description' content='A JavaScript Quiz Game'><title>Quiz Ninja</title><link rel='stylesheet' href='styles.css'></head><body> <section class='dojo'> <div class='quiz-body'> <header> <h1>Quiz Ninja!</h1> </header> </div> </section><script src='main.js'></script></body></html>
This is a standard HTML5 layout with a simple heading at the top of the page. We’ll add more to the page as the application develops in later chapters.
Now it’s time to style the page. Add the following code to the styles.css
file:
@import url('https://fonts.googleapis.com/css?family=Baloo+Da|Roboto');
body{ background: #5F1C1C; font-family: 'Roboto', sans-serif;}.dojo{ background: url(https://cdn.rawgit.com/alexmwalker/6acbe9040d9fe6e5e9fd758a25e1b2a5/raw/9c8131eb2ccc1e3839a5a5114cb16b5dc74daf04/dojo.svg) no-repeat; width: 100%; height: 800px; background-size: 100% auto; padding-top: 10px;}.quiz-body{ background: rgba(255,255,255,1); margin: 150px 33%; padding: 10px 20px 50px 20px; -webkit-box-shadow: 4px 4px 11px 3px rgba(0,0,0,0.3); -moz-box-shadow: 4px 4px 11px 3px rgba(0,0,0,0.3); box-shadow: 4px 4px 11px 3px rgba(0,0,0,0.3);}h1{ color: #611BBD; font-family: 'Baloo Da', cursive; font-weight: 900; text-align: center; font-size: 48px; margin: 0;}button { color: #ffffff; background-color: #611BBD; border-color: #130269; border-radius: 4px; margin: 0.2em 0; display: block; width: 100%; font-size: 24px;}#question { font-size: 24px;}
#result{ color: #fff; margin: 0.2em 0; width: 100%; text-align: center;}.correct { background-color: #0c0;}.wrong { color: #fff; background-color: #c00;}
This file covers all the styles that will be used throughout the project, so quite a few of the styles aren't used at first, but it means we won't need to edit this file again in the book.
And finally we’ll add some interactivity using JavaScript. Place the following code inside the main.js
file:
alert('Welcome to Quiz Ninja!');
The first line uses the alert()
function that displays a welcome message to the player in a dialog box in the browser. Although alert
isn’t actually part of the official ECMAScript specification, it’s used by all browsers as a way of showing messages.
To give this a try, open the index.html
file in your favorite browser. You should be greeted by the welcome message alert box, such as in the screenshot below.
You can also see a live example on CodePen.
This gives us a good solid start to our project that we can build on over the course of the book as our JavaScript knowledge develops.
Chapter Summary
JavaScript was created in 1995 by Brendan Eich, an employee of Netscape.
It quickly became popular and was soon considered to be the language of the web.
The browser wars caused many problems for JavaScript and resulted in lots of fragmented code that was hard to maintain.
The advent of Ajax and its use in Web 2.0 apps, such as Gmail and Google Maps, prompted a resurgence in JavaScript.
JavaScript’s main environment is the browser, but can also be used in other environments.
You only need a browser to write JavaScript but a good text editor or IDE and Node installation are recommended.
Graceful degradation and progressive enhancement are the process of ensuring users receive a decent experience even if they lack some of the requirements.
Unobtrusive JavaScript is when the JavaScript functionality is separated from the HTML content and CSS styling.
Each new version of JavaScript has to be compatible with older versions.
A transpiler can be used to convert code from one version of JavaScript into another. They are often used to transpile the latest version of the language into an older version that will work in most browsers.
In the next chapter we’re going to start looking at some programming fundamentals ― let’s get to it, ninja!