cover.eps

Title page image

Coding with JavaScript For Dummies®

Visit www.dummies.com/cheatsheet/codingwithjavascript to view this book's cheat sheet.

Introduction

JavaScript is hot! What started as a quick-and-dirty language created for one of the first web browsers has turned into the world’s most popular programming language. Demand for JavaScript programmers is at an all-time high and only continues to grow.

This book is your key to becoming proficient in the core concepts of JavaScript. Whether your goal is to land a high-paying job as a programmer or to make your own personal website more interactive, you can be confident that the content and techniques presented in this book are fully up to date with the most current JavaScript standards and best practices.

Each chapter contains complete examples of real code that you can try and test in your own web browser at home.

Just as the only way to Carnegie Hall is to practice, practice, practice, the only way to become a better programmer is to code, code, code!

About This Book

This book is a friendly and approachable guide to getting started with writing JavaScript code. As programming languages go, JavaScript is fairly easy to pick up and start using. Because it’s so accessible, many people who started as web page authors have found themselves in the position of being responsible for maintaining, modifying, and writing JavaScript code. If that describes you, this book will quickly and easily bring you up to speed.

Whether you know a little JavaScript or you’ve never seen it, this book shows you how to write JavaScript the right way.

Topics covered in this book include the following:

Learning JavaScript isn’t only about learning the syntax of the language. It’s also about accessing the tools and community that has been built around the language. Professional JavaScript programmers have greatly refined the tools and techniques used to write JavaScript over the language’s long and exciting history. Throughout the book, we mention important best practices and tools for testing, documenting, and writing better code faster!

To make this book easier to read, keep in mind the following:

Foolish Assumptions

We have a policy at our company, WatzThis?, to never assume (but, frankly, Eva is better at following the policy than Chris is). If you were ever 12 years old, you’ve probably heard the saying about what happens when you assume. If you don’t know, email us.

You don’t need to be a programming ninja or a hacker to understand programming. You don’t need to understand how the guts of your computer work. You don’t even need to know how to count in binary.

However, we do need to make a couple of assumptions about you. We assume that you can turn your computer on, that you know how to use a mouse and a keyboard, and that you have a working Internet connection and web browser. If you already know something about how to make web pages (it doesn’t take much!), you have a jump start on the material.

The other things you need to know to write and run JavaScript code are details we cover in this book. And the one thing you’ll find to be true is that programming requires attention to details.

Icons Used In This Book

Here’s a list of the icons we use in this book to flag text and information that’s especially noteworthy:

tip This icon highlights helpful tips that show you easy ways or shortcuts that will save you time or effort.

remember Whenever you see this icon, pay special attention. You won’t want to forget the information you’re about to read.

warning Be careful — very careful. This icon warns you of pitfalls to avoid.

technicalstuff This icon highlights technical details that you may or may not find interesting. Feel free to skip this information, but if you’re the techie type, you might enjoy reading it.

Beyond the Book

Here’s where you can find the online content for this book:

Where to Go from Here

Coding with JavaScript is fun, and once you get a little knowledge under your belt, the world of interactive web applications is your oyster! So buckle up! We hope you enjoy the book and our occasional pearls of wisdom.

Part I

Getting Started with JavaScript

image

webextra Visit http://www.dummies.com for great Dummies content online.

In this part …

check.png Find out how to write your first JavaScript program.

check.png Get the inside scoop on how to work with variables and arrays.

check.png Discover how to work with operators, expressions, and statements.

check.png Use loops and branches in your JavaScript coding.

check.png Visit http://www.dummies.com for great Dummies content online.

Chapter 1

The World's Most Misunderstood Programming Language

In This Chapter

arrow Getting to know JavaScript

arrow Figuring out what JavaScript does

arrow Understanding why you need JavaScript

“People understand me so poorly that they don't even understand my complaint about them not understanding me.”

— Søren Kierkegaard

JavaScript hasn’t always been as highly regarded as it is today. Some people have called it the best and worst programming language in the world. Over the last few years, there have been a great number of improvements made to the way programmers write JavaScript and to JavaScript interpreters. These improvements have made JavaScript a much better language today than it’s been in the past.

In this chapter, you discover what JavaScript is and a little bit of the history of the language. You also find out what JavaScript does and why you need to know it.

What Is JavaScript?

Back in the very early days of the web, browsers were simple readers for web pages (see Figure 1-1). They had virtually no capabilities themselves, except for the ability to display text in various sized fonts. As soon as Microsoft released its Internet Explorer browser, the browser wars were on, and the features started flying! One browser introduced the ability to display images, then another introduced the capability to have different fonts, and then blinking text, moving text, and all sorts of other wacky capabilities were introduced!

image

Figure 1-1: The first web browsers weren’t much to look at.

It wasn’t long before someone got the idea that browsers could actually do useful things themselves, rather than just acting as fancy document display programs.

The Eich-man cometh

JavaScript got its start back in 1995 at Netscape. The creator of JavaScript, Brandon Eich, wrote JavaScript in record time (some say in as few as ten days!) by borrowing many of the best features from various other programming languages. The rush to market also created some interesting quirks (or, less politely described, mistakes) in the design of the language. The result is a sort of Esperanto-like language that looks deceptively familiar to people who are experienced with other programming languages.

Mocha-licious

The original name of JavaScript was Mocha. It was renamed LiveScript with the first beta deployment of Netscape Navigator and was then changed to JavaScript when it was built into the Netscape 2 browser in 1995. Microsoft very quickly reverse-engineered JavaScript and introduced an exact clone of it in Internet Explorer, calling it Jscript in order to get around trademark issues.

Netscape submitted JavaScript to the standards organization known as Ecma International, and it was adopted and standardized as EMCAScript in 1997.

technicalstuff Brandon Eich, the creator of JavaScript, famously commented about the name of the standardized language; stating that ECMAScript was an “unwanted trade name that sounds like a skin disease.”

warning Not only is ECMAScript an unappealing name for a programming language, the name given to the language by Netscape and which most people refer to it as, is rather unfortunate as well. If you already know how to program in Java or if you learn how to at some point, it’s a very good idea to keep in mind that the two languages may have some similarities, but they are, in fact, quite different animals.

We need more effects!

When JavaScript debuted, it quickly became very popular as a way to make web pages more dynamic. So-called Dynamic HTML (DHTML) was an early result of JavaScript being built into web browsers, and it enabled all sorts of fun effects, like the falling snowflake effect (see Figure 1-2), pop-up windows, and curling web page corners, but also more useful things like drop-down menus and form validation.

image

Figure 1-2: JavaScript made it possible to have snowflakes falling on your web page.

JavaScript grows up

Now entering its third decade, JavaScript has become the world’s most widely used programming language and virtually every personal computer in the world has at least one browser on it that can run JavaScript code.

JavaScript is flexible enough that it can be used and learned by nonprogrammers, but powerful enough that it can (and is) used by professional programmers to enable functionality on nearly every website on the Internet today, ranging from single-page sites to gigantic sites like Google, Amazon, Facebook, and many, many others!

Dynamic scripting language

JavaScript is often described as a dynamic scripting language. In order to understand what this means, we need to first define a couple of terms and provide some context.

Computer programs are sets of instructions that cause computers to do things. Every computer programming language has a set of instructions and a certain way that humans must write those instructions. The computer can’t understand these instructions directly. In order for a computer to understand a programming language, it needs to go through a conversion process that translates human-readable (and writable) instructions into machine language. Depending on when this translation takes place, programming languages can be roughly divided into two types: compiled and interpreted (see Figure 1-3).

image

Figure 1-3: Programming languages are classified according to when the compilation takes place.

Compiled programming languages

Compiled programming languages are languages in which a programmer must write the code and then run it through a special program called a compiler that interprets the given code and then converts it into machine language. The computer can then execute the compiled program.

Examples of compiled languages include C, C++. Fortran, Java, Objective-C, and COBOL.

Interpreted programming languages

Interpreted languages are technically still compiled by the computer into machine language, but the compiling takes place by the user’s web browser right as the program is being run. Programmers who write interpreted languages don’t need to go through the step of compiling their code prior to handing it off to the computer to run.

The benefit of programming in an interpreted language is that it’s easy to make changes to the program at any time. The downside, however, is that compiling code as it’s being run creates another step in the process and can slow down the performance of programs.

Partially because of this performance factor, interpreted languages have gotten a reputation for being less than serious programming languages. However, because of better just-in-time compilers and faster computer processors, this perception is rapidly changing. JavaScript is having a big impact in this regard.

Examples of interpreted programming languages include PHP, Perl, Haskell, Ruby and of course, JavaScript

What Does JavaScript Do?

If you use the web, you're making use of JavaScript all the time. The list of things that can be enabled with JavaScript is extensive and ranges from simple notices you get when you forget to fill out a required field on a form to complex applications, such as Google Docs or Facebook. Here’s a short list of the most common uses for JavaScript on the web:

image

Figure 1-4: So-called Magic Zoom effects are enabled using JavaScript.

Why JavaScript?

JavaScript has become the standard for creating dynamic user interfaces for the web. Pretty much any time you visit a web page with animation, live data, a button that changes when you hover over it, or a drop-down menu, JavaScript is at work. Because of its power and ability to run in any web browser, JavaScript coding is the most popular and necessary skill for a modern web developer to have.

JavaScript is easy to learn

Keep in mind that programming languages were created in order to give people a simple way to talk to computers and tell them what to do. Compared with machine language, the language that the computer’s CPU speaks, every programming language is easy and understandable. To give you a sample of what sort of instructions your computer is actually obeying, here is a machine language program to write out "Hello World".

b8   21 0a 00 00
a3   0c 10 00 06
b8   6f 72 6c 64
a3   08 10 00 06
b8   6f 2c 20 57
a3   04 10 00 06
b8   48 65 6c 6c
a3   00 10 00 06
b9   00 10 00 06
ba   10 00 00 00
bb   01 00 00 00
b8   04 00 00 00
cd   80
b8   01 00 00 00
cd   80

Now look at one way you can accomplish this simple task with JavaScript:

alert("Hello World");

Much easier, yes?

tip Once you learn the basic rules of the road (called the syntax), such as when to use parentheses and when to use curly brackets ({}), JavaScript actually resembles plain old English.

remember The first step in learning any language, including programming languages, is to get over your fear of getting started. JavaScript makes this easy. There are thousands of sample bits of JavaScript code on the web that anyone can just pick up and start messing around with. You already have all the tools you need (see Chapter 2), and it’s easy to start small with JavaScript and gradually build up to making great and wonderful things.

Where is JavaScript? JavaScript is everywhere!

Although JavaScript was originally designed to be used in web browsers, it has found a home in many other places. Today, JavaScript runs on smartphones and tablets, on web servers, in desktop applications, and in all sorts of portable devices.

JavaScript in the web browser

The most common place to find JavaScript, and what it was originally designed to do, is running in web browsers. When JavaScript runs in this way, it’s called client-side JavaScript.

Client-side JavaScript adds interactivity to web pages. It accomplishes this in several ways:

  • By controlling the browser itself or making use of functionality of the browser
  • By manipulating the structure and content of web pages
  • By manipulating the styles (such as fonts and layout) of web pages
  • By accessing data from other sources

In order to understand how JavaScript is able to manipulate the structure and style of web pages, you need to know a little bit about HTML5 and CSS3.

HTML5

Hypertext Markup Language (HTML) is the language used to structure web pages. It works by marking up content (text and images) to give web browsers information about the content, such as what is a heading, what is a paragraph, where an image goes, and so on. Listing 1-1 shows a simple HTML document. Figure 1-5 shows how a web browser displays this document.

image

Figure 1-5: Web browsers use HTML to render web pages.

Listing 1-1: A Simple HTML Document

<!DOCTYPE html>
<html>
<head>
 <title>Hello, HTML!</title>
</head>
<body>
 <h1>This is HTML</h1>
 <p id="introduction">This simple document was written with Hypertext Markup Language.</p> 
</body>
</html>

Here is everything you need to know about HTML right now in order to move forward with learning JavaScript:

  • In HTML, the characters surrounded by angle brackets are called tags.
  • The ending tag (which comes after the content being marked up) has a slash after the first angle bracket. For example </p> is an ending tag.
  • A group of two tags (beginning and ending), plus the content in between them, is called an element.
  • Elements are generally organized in a hierarchal way (with elements nested within elements).
  • Elements may contain name/value pairs, called attributes. If an element has attributes, they go in the beginning tag. Name/value pairs assign values, in quotes, to names (which aren’t in quotes) by putting an equals sign between them. For example, in the following tag, width and height are both attributes of the div element:

    <div width="100" height="100"></div>

  • Some elements don’t have content and therefore don’t need an ending tag. For example, the img tag, which simply inserts an image into a web page, looks like this:

    <img src="myimage.jpg" width="320" height="200" alt="Here is a picture of my dog.">

All the data necessary to show the image is included in the beginning tag using attributes, so the img tag doesn’t require an ending tag.

When you write a web page with HTML, you can include JavaScript code directly in that document, or you can reference JavaScript code file (which end in .js) from the HTML document. Either way, your viewer’s web browser will download the JavaScript code and run it when a user accesses a web page containing that JavaScript.

remember Client-side JavaScript runs inside of your users’ web browsers.

CSS3

Cascading Style Sheets (CSS) is the language used to add formatting and different layouts to web pages. The word style, when used in CSS, refers to many aspects of how the HTML document is presented to the user, including

  • Typefaces (or font faces)
  • Type size
  • Colors
  • Arrangement of elements in the browser window
  • Sizes of elements
  • Borders
  • Backgrounds
  • Creation of rounded corners on element borders

Like JavaScript, CSS can be either placed directly into an HTML document, or it can be linked to from the HTML document. Once it’s downloaded, it immediately does its thing and formats the document according to your specifications.

Style sheets in CSS are made up of CSS rules, which contain properties and values that should be applied to an element or a group of elements. Here’s an example of a CSS rule:

p{font-size: 14px; font-color: black; font-family: Arial, sans-serif}

This rule, reading from left to right, specifies that all p elements (which indicate paragraphs in HTML) should be displayed in text that is 14px large, black, and using the Arial font. If Arial isn’t available on the user’s computer, it should be displayed in some sans serif typeface.

The part of the CSS rule that’s outside of the curly brackets is called the selector. It selects the elements that the properties within the curly brackets apply to.

technicalstuff Throughout this book, you find out how to use JavaScript with HTML and CSS. We provide just enough information here to be able to show you how HTML and CSS work. If you need to learn more, you can find some excellent books about them. One that we highly recommend is Beginning HTML5 and CSS3 For Dummies by Ed Tittel and Chris Minnick (Wiley).

JavaScript is powerful!

JavaScript running in a web browser used to be slow, and JavaScript got a bad reputation early on among programmers. Today, JavaScript code runs 80 percent as fast as compiled code. And, it keeps getting faster all the time. What this means is that today’s JavaScript is much more powerful than the JavaScript of just a few years ago. And, it’s many times more powerful than the JavaScript that was first introduced in 1995.

JavaScript is in demand

JavaScript is not only the most widely known programming language, it’s also one of the most in-demand skills in the job market. It’s projected that the job market for JavaScript programmers will increase by 22 percent between 2010 and 2020. Exciting things are happening with JavaScript, and there has never been a better time than right now to learn it.

Chapter 2

Writing Your First JavaScript Program

In This Chapter

arrow Arranging your development environment

arrow Getting to know JavaScript code

arrow Understanding a simple JavaScript program

arrow Understanding the value of commenting your code

“The secret of getting ahead is getting started.”

— Mark Twain

Simple JavaScript programming isn’t difficult to understand. In this chapter, you go through the process of setting up your computer for writing JavaScript. You also write your first JavaScript program and get to know the basic syntax behind everything you’ll do with JavaScript in your future as a programmer.