Coding with JavaScript For Dummies®
Published by: John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030-5774, www.wiley.com
Copyright © 2015 by John Wiley & Sons, Inc., Hoboken, New Jersey
Media and software compilation copyright © 2015 by John Wiley & Sons, Inc. All rights reserved.
Published simultaneously in Canada
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without the prior written permission of the Publisher. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at
http://www.wiley.com/go/permissions
.
Trademarks: Wiley, For Dummies, the Dummies Man logo, Dummies.com, Making Everything Easier, and related trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and may not be used without written permission. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book.
LIMIT OF LIABILITY/DISCLAIMER OF WARRANTY: THE PUBLISHER AND THE AUTHOR MAKE NO REPRESENTATIONS OR WARRANTIES WITH RESPECT TO THE ACCURACY OR COMPLETENESS OF THE CONTENTS OF THIS WORK AND SPECIFICALLY DISCLAIM ALL WARRANTIES, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE. NO WARRANTY MAY BE CREATED OR EXTENDED BY SALES OR PROMOTIONAL MATERIALS. THE ADVICE AND STRATEGIES CONTAINED HEREIN MAY NOT BE SUITABLE FOR EVERY SITUATION. THIS WORK IS SOLD WITH THE UNDERSTANDING THAT THE PUBLISHER IS NOT ENGAGED IN RENDERING LEGAL, ACCOUNTING, OR OTHER PROFESSIONAL SERVICES. IF PROFESSIONAL ASSISTANCE IS REQUIRED, THE SERVICES OF A COMPETENT PROFESSIONAL PERSON SHOULD BE SOUGHT. NEITHER THE PUBLISHER NOR THE AUTHOR SHALL BE LIABLE FOR DAMAGES ARISING HEREFROM. THE FACT THAT AN ORGANIZATION OR WEBSITE IS REFERRED TO IN THIS WORK AS A CITATION AND/OR A POTENTIAL SOURCE OF FURTHER INFORMATION DOES NOT MEAN THAT THE AUTHOR OR THE PUBLISHER ENDORSES THE INFORMATION THE ORGANIZATION OR WEBSITE MAY PROVIDE OR RECOMMENDATIONS IT MAY MAKE. FURTHER, READERS SHOULD BE AWARE THAT INTERNET WEBSITES LISTED IN THIS WORK MAY HAVE CHANGED OR DISAPPEARED BETWEEN WHEN THIS WORK WAS WRITTEN AND WHEN IT IS READ.
For general information on our other products and services, please contact our Customer Care Department within the U.S. at 877-762-2974, outside the U.S. at 317-572-3993, or fax 317-572-4002. For technical support, please visit
www.wiley.com/techsupport
.
Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at
http://booksupport.wiley.com
. For more information about Wiley products, visit
www.wiley.com
.
Library of Congress Control Number: 2015938674
ISBN: 978-1-119-05607-2
ISBN 978-1-119-05607-2 (pbk); ISBN 978-1-119-05605-8 (ePDF); ISBN 978-1-119-05606-5 (ePub)
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!
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:
document.write("Hi!");
document.getElementById("anElementInTheDocument").
addEventListener("click",doSomething,false);
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.
Here’s a list of the icons we use in this book to flag text and information that’s especially noteworthy:
Here’s where you can find the online content for this book:
www.dummies.com/go/codingwithjavascript
. Here you will find a directory labeled by chapter. Within the chapter, you will find each example labeled by its listing numberwww.dummies.com/cheatsheet/codingwithjavascript
.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
In this part …
Find out how to write your first JavaScript program.
Get the inside scoop on how to work with variables and arrays.
Discover how to work with operators, expressions, and statements.
Use loops and branches in your JavaScript coding.
Visit http://www.dummies.com
for great Dummies content online.
Chapter 1
In This Chapter
Getting to know JavaScript
Figuring out what JavaScript does
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.
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!
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.
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.
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.
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.
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!
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).
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 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
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:
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.
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?
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.
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:
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.
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.
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:
</p>
is an ending tag.width
and height
are both attributes of the div
element:
<div width="100" height="100"></div>
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.
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
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.
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 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
In This Chapter
Arranging your development environment
Getting to know JavaScript code
Understanding a simple JavaScript program
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.