Introduction to JavaScript - JavaScript Basics - JavaScript, 20 Lessons to Successful Web Development (2015)

JavaScript, 20 Lessons to Successful Web Development (2015)

PART I JavaScript Basics

LESSON 1 Introduction to JavaScript

image

To view the accompanying video for this lesson, please visit mhprofessional.com/nixonjavascript/.

At the dawn of the Internet, webmasters were a strange breed (and few and far between) and nobody really knew what their mastery entailed. But their development toolkit was nothing compared to what we have today; they had a knowledge of HTML (HyperText Markup Language) and a basic understanding of the HTTP (HyperText Transfer Protocol) interface for serving up web pages, and really that was all—there actually wasn’t a lot to building web pages.

You see, there were no such things as plug-ins or style sheets, and the Web was actually quite a dull and drab experience as a consequence, but it was so new and fascinating that design, layout, and dynamic interactivity weren’t important. All users wanted was more and more information (and funny cat pictures). In fact, what most casual web users probably know today would likely have been considered webmaster skills in the early 1990s.

But time marches on and, in the case of the Web, it does so at Internet Time (which is several times faster than normal), and pretty soon the latest browsers supported loading plug-ins for greater functionality, such as playing audio or video, style sheets were adopted to vastly improve the display of fonts and web layout and design, new graphical enhancements were developed such as the animated GIF (graphics interchange format), and probably most important of all was the introduction of a scripting language.

It was realized quite early on that, as powerful as HTML was, it simply didn’t offer the interactivity that users were calling out for. Something new was needed, but what? Clearly a programming language of some sort had to be the answer, but not just any old language—a new one would have to be designed from the ground up in order to hook directly into HTML, so that the two could work together seamlessly. And that language came to be known as JavaScript.

In the Beginning

The JavaScript programming language was written by Brendan Eich at Netscape and was previously known by both of the names Mocha and LiveScript. It was first incorporated into the Netscape Navigator browser (see Figure 1-1) in 1995, at the same time that Netscape added support for Sun’s Java technology.

image

FIGURE 1-1 Netscape Navigator 4.08

JavaScript is a quite different language from Java, but, as part of a marketing deal made between Netscape and Sun Microsystems, it was given its name to try and benefit from the general buzz surrounding the Java language.

To justify this naming, in JavaScript, all Java keywords are reserved, its standard library follows Java’s naming conventions, and its Math and Date objects are based on Java 1.0 classes. Also, the trademark name JavaScript belongs to Oracle, but the similarities end there.

image

Because the name JavaScript is trademarked (by Oracle since its purchase of Sun, which developed Java), when the language was submitted to ECMA, the European Computer Manufacturers Association (a nonprofit standards organization), the standard was officially given the name ECMAScript. However, you rarely hear people referring to the standard as such in general use (ECMAScript simply doesn’t have the same ring to it as JavaScript). Technically, therefore, both JavaScript and JScript are dialects of ECMAScript, but in the same way that the trademarked word Aspirin fell into common use for acetylsalicylic acid in many countries, all dialects of this scripting language tend to be referred to simply as JavaScript.

Microsoft’s version, called JScript, was released a year later as a component of Internet Explorer (IE) 3.0 and, as you might expect, it differed in several important respects, making it less than 100 percent compatible with JavaScript. Unfortunately, that remains true to this day; although IE9 addressed many of the prior incompatibilities and IE10 became even more compatible with the other browsers, IE11 (the latest at the time of writing, see Figure 1-2) still retains a number of niggling differences that developers have to take into account.

image

FIGURE 1-2 Microsoft Internet Explorer 11

In-browser Scripting

Unlike other languages used for creating websites, such as Perl, PHP, and Ruby, JavaScript runs within the web browser and not on a web server. This makes it the perfect tool for creating dynamic web pages because it can modify HTML elements in real time. It is also the technology behind Web 2.0 Ajax functionality, in which data is transferred between a web server and web browser behind the scenes, without the user being aware of it.

JavaScript’s great power lies in its ability to access HTML’s Document Object Model (DOM), in which every element on a web page can be individually addressed (either reading or modifying its value), and elements can also be created and deleted on the fly, as well as layered over each other and moved about.

You can even go so far as to treat a web browser window as a blank canvas and build entire applications and arcade games from scratch, using JavaScript and the DOM (although it takes some quite advanced programming skills). What’s more, with new HTML5 features such as the canvas and geolocation, JavaScript has become even more of a backbone for modern, dynamic web pages.

Info for Programmers

If you can already program in another language such as C or Java, for example, you’ll find yourself at home with JavaScript, and here are a few things you should know about the language that will make your learning process even quicker. If you are not a programmer, you may skip to the section “Why You Need to Know JavaScript,“ as these terms will be explained later in the book.

To begin with, JavaScript supports much of the structured programming syntax used in C, such as if() statements, while() and for() loops, switch() statements, and so on. Unlike many languages, it is not necessary to terminate statements with a semicolon, unless more statements will follow on the same line.

JavaScript is a scripting language that used to be interpreted but is nowadays compiled on the fly by the latest browsers. In common with other scripting languages, it uses dynamic typing in which types are associated with values rather than variable names. Values are interpreted as integers, floating point, strings, or other types according to the way in which they are used within an expression.

All About Objects

The JavaScript language is based on objects that are associative arrays. Properties of objects can be accessed using either the period operator (for example, object.height) or with square brackets (for example, object[′height′]). Object properties can be enumerated using for(… in …) loops.

In JavaScript, functions are themselves objects, so they have properties such as length and methods such as call(). This means they may also be assigned to variables, passed as arguments, and returned by other functions. Functions are referenced by naming them without parentheses (for example, a = funcname) or invoked by adding the parentheses (for example, a = funcname()).

The former case sets the variable a to contain a copy of the function object with the name funcname, whereas the latter assigns the result returned by calling the function to the variable a. You may create inner functions within other functions, and these retain the scope of the outer function, including its constants, local variables, and argument values.

Rather than implementing classes, JavaScript uses prototypes for inheritance. Functions can double as object constructors, and prefixing a function with the new keyword creates a new object, calling that function with its local this keyword.

Why You Need to Know JavaScript

Although it is possible to get by with a basic knowledge of HTML and maybe a smattering of CSS (Cascading Style Sheets), if you are at all serious about developing professional-looking websites that attract repeat visitors and build an audience, then there’s no getting around the fact that you have to learn JavaScript in order to access all the latest goodies your users will expect.

Following is a list of just some of the features you may wish to include in a web page, and which require the use of JavaScript to one extent or another:

Animations Some animation can be achieved with CSS transitions, but for true interactivity, you need to control graphics directly using JavaScript.

Geolocation To provide location-aware services to your users, you must access the data using JavaScript.

Canvas The only way to draw on the HTML5 canvas is with JavaScript commands.

Audio and Video You can add these with simple HTML5 tags, but to control playback directly, you will need JavaScript.

Form Processing If you wish to make your forms easier to use by having in-browser validation, user prompting, and error checking, then you have to do much of this with JavaScript, although HTML5 is making some great inroads in this direction.

Ajax Any behind-the-scenes communication with a web server you need to make has to be done via JavaScript calls.

Dynamic Elements Some elements can be changed via CSS and mouse-overs, but for anything more, such as resizing, moving, or dragging and dropping, you have to use JavaScript.

In-browser Gaming Games that run in the browser without plug-ins such as Flash are written in JavaScript (see Figure 1-3).

Floating Elements Pop-ups and other floating elements that follow the page as you scroll are all implemented with JavaScript.

Hover Effects Thumbnail or advanced tooltips that hover over HTML elements are created and controlled with JavaScript.

image

FIGURE 1-3 A Pacman-style game written in JavaScript

And this list is by no means exhaustive; just take a look at tinyurl.com/cooljsexamples to see some very clever features that have been built with JavaScript, or check out everyday websites such as Facebook, Gmail, and Twitter, all of which subtly use JavaScript behind the scenes to provide their slick interfaces.

For example, if you have a Gmail account, next time you log in, right-click and select the View Source option in your browser to see how the page is constructed. As well as all the JavaScript files that Gmail calls up from its server, the main web page itself is completely packed with JavaScript, as shown in Figure 1-4.

image

FIGURE 1-4 Viewing Gmail’s JavaScript source code

But don’t let that picture put you off, Google packs its JavaScript as tightly as possible to save on bandwidth and to make it difficult for the casual observer to determine what’s going on. I guarantee that the original source code will be neatly laid out one line at a time and clearly documented so that a team of programmers can work with it. It’s probably only when the time comes to publish an update that the nice and tidy code gets run through another program to squish it into production web pages.

Summary

As I said, if you are new to programming, don’t worry about any of these terms because I explain them later in the book at the appropriate places. And I promise, they are just words, and their use will become second nature to you as you learn JavaScript, because it really is a simple language to learn.

Self-Test Questions

Test how much you have learned in this lesson with these questions. If you don’t know an answer, go back and reread the relevant section until your knowledge is complete. You can find the answers in Appendix A.

1. What is the name of the official language of which JavaScript and Jscript are dialects?

2. From where does JavaScript get its name?

3. Who owns the trademark for the JavaScript name?

4. Why did a new programming language have to be invented?

5. What does the acronym HTML stand for?

6. What does the acronym HTTP stand for?

7. What does the acronym CSS stand for?

8. What does the acronym DOM stand for?

9. On what are JavaScript’s Math and Date objects based?

10. How can you view the source HTML/JavaScript of a web page?