The aim of this book is to introduce you to programming using the JavaScript language,eventually helping you to develop into a JavaScript ninja.. This is an exciting time to be learning
Trang 2Preface
Trang 31 Hello JavaScript
Trang 42 Programming Basics
Trang 53 Arrays, Logic, and Loops
Trang 64 Functions
Trang 75 Objects
Trang 86 The Document Object Model
Trang 97 Events
Trang 108 Forms
Trang 119 The Window Object
Trang 1210 Testing and Debugging
Trang 1311 Functional JavaScript
Trang 1412 Object-oriented Programming in JavaScript
Trang 1513 Ajax
Trang 1614 HTML5 APIs
Trang 1715 Organizing Your Code
Trang 1816 Next Steps
Trang 20BY DARREN JONES
Trang 22All rights reserved No part of this book may be reproduced, stored in a retrieval system or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embodied in critical articles or reviews.
Trang 23The author and publisher have made every effort to ensure the accuracy of the information herein However, the information contained in this book is sold without warranty, either express or implied Neither the authors and SitePoint Pty Ltd., nor its dealers or distributors will be held liable for any damages to be caused either directly or indirectly by the instructions contained in this book, or by the software or hardware products described herein.
Trang 24Rather than indicating every occurrence of a trademarked name as such, this book uses the names only in an editorial fashion and to the benefit of the trademark owner with no intention of infringement of the trademark.
Published by SitePoint Pty Ltd.
48 Cambridge Street Collingwood VIC Australia 3066 Web: www.sitepoint.com Email: business@sitepoint.com
Trang 25Darren has been playing around with programming and building websites for over a
decade He wrote the SitePoint book Jump Start Sinatra, and also produced the Getting
Started With Ruby video tutorials for Learnable, as well as writing a number of articles
published on SitePoint
In recent years, having seen just how powerful the language can be, Darren has started touse JavaScript much more heavily He believes that JavaScript will be the most importantprogramming language to learn in the future
Trang 26SitePoint specializes in publishing fun, practical, and easy-to-understand content for webprofessionals Visit http://www.sitepoint.com/ to access our blogs, books, newsletters,articles, and community forums You’ll find a stack of information on JavaScript, PHP,Ruby, mobile development, design, and more
To my two favourite super heroes, Zac & Sienna ― love you
loads x
Trang 27The aim of this book is to introduce you to programming using the JavaScript language,eventually helping you to develop into a JavaScript ninja
This is an exciting time to be learning JavaScript, having finally outgrown its earlyreputation as a basic scripting language used to produce cringeworthy effects on webpages Today, JavaScript is used to produce professional and powerful web applications.Modern browsers are now capable of running JavaScript code at lightning speed, andNode.js has helped to revolutionize it by facilitating its use in other environments Thishas led to a much more professional and structured approach to building JavaScriptapplications, where it is now considered a full-fledged programming language In short,JavaScript has grown up
JavaScript has a number of cool features that make it stand out from other languages, such
as callbacks, first-class functions, prototypal inheritance, and closures Its event-basedmodel also makes it a very good choice for modern web application development.JavaScript’s ace in the pack, though, is something of which every language is envious―its
ubiquity JavaScript is available almost everywhere; anybody who has access to a browser
can use it And this is increasing every year as it becomes more readily available outsidethe browser environment This translates into JavaScript’s reach being immense: it isalready the most popular language on GitHub I can only see JavaScript growing evenmore popular in the future as it becomes the language of choice for the Internet of Things
—helping to control household appliances, even program robots
Before I get carried away, though, I should point out that JavaScript is far from perfect,having a number of flaws It is missing some important programming constructs, such asmodules and private functions, that are considered standard in many modern programminglanguages Yet it’s also an unbelievably flexible language, where many of these gaps can
be filled using the tools that it provides In addition, many libraries have sprung intoexistence that help to extend JavaScript so that it’s now able to reach its full potential.This book starts off with the basics, assuming no programming or JavaScript knowledge,but quickly gets up to speed covering all the main topics in great depth such as functions,objects, and DOM manipulation More advanced topics such as error handling and testing,functional programming, and OOP are then introduced after the basics have been covered.There have been some exciting new developments in the world of JavaScript over the lastfew years such as Ajax, HTML5 APIs, and task runners, and these are covered in the lastpart of the book There’s also a practical project to build a quiz application that isdeveloped throughout the book towards the end of each chapter I’ve written withdeveloping for modern browsers in mind, so I’ve always tried to use the most up-to-datemethods in the examples Having said that, I’ve also tried to acknowledge if somethingmight not work in an older browser, or if a workaround is needed
It’s a long way ahead―16 chapters, to be precise But remember, every ninja’s journeystarts with a single page (or something like that, anyway) So, turn the page and let’s getstarted!
Trang 28This book is suitable for beginner-level web designers and developers Some knowledge
of HTML and CSS is assumed, but no previous programming experience is necessary
Trang 29You’ll notice that we’ve used certain typographic and layout styles throughout this book tosignify distinct types of information Look out for the following items
Trang 30Notes are useful asides that are related, but not critical, to the topic at hand.Think of them as extra tidbits of information
Important: Make Sure You Always …
… pay attention to these important points
Warning: Watch Out!
Warnings will highlight any gotchas that are likely to trip you up along theway
Trang 32Thanks for buying this book—we appreciate your support Do you want to continuelearning? You can now gain unlimited access to courses and ALL SitePoint books atLearnable for one low price Enroll now and start learning today! Join Learnable andyou’ll stay ahead of the newest technology trends: http://www.learnable.com
Trang 33Hello JavaScript
Now it’s time to start learning JavaScript In this chapter, we’re going to introduce thelanguage, as well as set up a programming environment We’ll also write our firstprograms in JavaScript
Trang 34Programming is about making computers do what you want A computer program isbasically 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 1sand 0s The first computers were programmed using punched cards, with a holerepresenting a 1 and no hole representing 0 Machine code and assembly language arelow-level programming languages that are closely associated with a computer’s hardware.These can be difficult in which to program because they involve writing very abstract codethat is heavily tied to a computer’s architecture
Alternatively, high-level programming languages allow abstractions such as functions andlogical statements to be used, making code easier for humans to read and write Programsare written in a language such as C, C++ or Java, which is then compiled into machinecode and executed These programs are usually very fast and are often used to write gamesand professional business software where speed is important
Interpreted high-level languages that are translated into machine code at run time are often
referred to as scripting languages They typically run slower than compiled languages,
although interpreters are becoming more and more sophisticated, increasingly blurring theline between compiled and interpreted languages
Trang 35The 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 themost popular programming languages in the world It has a low barrier to entry―all youneed to program in JavaScript is a text editor and a web browser Although it is easy to getstarted, JavaScript can be a tricky language to grasp as it has some unique features andinteresting quirks Once you have mastered it, though, you’ll find it is a very flexible andexpressive language that can create some powerful applications
JavaScript is a high-level language that is compiled at run time This means that it requires
an engine that is responsible for interpreting programs and running them The mostcommon JavaScript engines are found in browsers such as Firefox, Chrome, or InternetExplorer, although JavaScript can be run without a browser Many modern JavaScriptengines use a Just-in-time (JIT) interpreting process, which considerably speeds up thecompilation process, making the programs run faster
JavaScript is also a dynamic language, which means that elements of a program canchange while it is running
The History of JavaScript
The World Wide Web was originally a bunch of pages linked together by hyperlinks Soonpeople wanted more interaction and so Netscape (an early browser vendor) asked BrendanEich to develop a new language for their Navigator browser This needed to be donequickly because of the intense competition between Netscape and Microsoft to be first tomarket, and Eich managed to create a prototype language in just ten days In order to dothis, he borrowed various elements from other languages, including AWK, Java, Perl,Scheme, HyperTalk, and Self The new language was originally called LiveScript, but washastily rebranded as JavaScript so that it could benefit from the publicity that the SunMicrosystem’s Java language was attracting at the time This name has often caused someunfortunate confusion, with JavaScript often thought of as a lighter version of Java; thetwo languages are unrelated, although JavaScript does share some syntax with Java
JavaScript made its debut in version 2 of Netscape’s Navigator browser in 1995 Thefollowing year, Microsoft reverse-engineered JavaScript to create their own version, calledJScript to avoid copyright issues with Sun Microsystems who owned the Java trademarkand had licensed it to Netscape JScript shipped with version 3 of the Internet Explorerbrowser and was almost identical to JavaScript―it even included all the same bugs andquirks―but did have some extra Internet Explorer-only features Microsoft includedanother scripting language called VBScript with Internet Explorere at the same time,although this never really caught on
JavaScript (and JScript) was immediately popular It had a low barrier to entry and wasrelatively easy to learn, which meant an explosion in its usage making web pages dynamicand more interactive Unfortunately, its low barrier was also a curse as it meant that peoplecould write snippets of code without much understanding of what they were actuallydoing Code could be easily copied and pasted and was often used incorrectly, leading tolots of poor code examples appearing all over the Web JavaScript was also frequently
Trang 36The ECMAScript standard can be difficult to interpret in places, so the implementations ofJavaScript can vary in assorted JavaScript engines This is why some web browsersbehave differently when running JavaScript programs.
The Browser Wars
By the time Netscape Navigator 4 and Internet Explorer 4 were released, JavaScript hadbecome incredibly popular Microsoft had started a lot of hype about the term DynamicHTML, or DHTML for short, to refer to the use of JavaScript to make HTML moreinteractive and dynamic In an attempt to seize upon this popularity, Netscape andMicrosoft tried to add new proprietary features, which lead to different syntaxes beingused This “arms race” of adding new features to compete became known as the BrowserWars The unfortunate downside was that programmers had to write two versions of code
to achieve the same results in each browser Professional programmers often dismissedJavaScript as a toy language unsuitable for any serious programming, but this was unfaircriticism―the language wasn’t the problem, it was the way it was being implemented andused
Eventually, Microsoft won the browser wars and Internet Explorer emerged as thedominant browser Support for standards had also increased, helped largely by the efforts
of the Web Standards Project (WaSP) Developer and browser vendors started to worktogether 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 Safaribrowser in 2003 These both had strong standards support, which meant that developerswere able to produce better web applications using JavaScript that behaved consistentlyacross different browsers
Web 2.0
In 2005, sites such as Google Maps, Flickr, and Gmail started to appear and successfullydemonstrated 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 Thisdescribed a technique of obtaining data from a server in the background and updating onlythe relevant parts of the web page without the need for a full page reload, enabling theuser to still interact with the rest of the page This created a more seamless experience forusers where it was used extensively in many Web 2.0 applications As a result a lot of
Trang 37professional programmers took more notice of JavaScript and it began to be seen as apowerful and flexible programming language, capable of producing high-quality code.
Standards
As JavaScript became used for more sophisticated applications and browsers embracedstandards, the JavaScript landscape changed A new browser war started, but this time itwas about seeing which browser could be the most standards-compliant There has alsobeen competition to increase the speed of the JavaScript engine that is built into thedifferent browsers This started in 2008 when engineers at Google developed the V8engine to run inside the Chrome browser It was significantly faster than previousJavaScript engines and signalled another arms race as other browser vendors responded byincreasing the speed of their engines JavaScript now runs significantly faster in modernbrowsers and the pace of improvement shows no sign of slowing down
HTML5
HTML5 is the latest HTML specification, although it is actually more of an umbrella termfor all the latest technologies that are used on the Web This includes HTML, CSS3modules, and lots of APIs that use JavaScript to interact with web pages These will becovered in more detail in Chapter 10
HTML5 has proven to be very popular and is emerging as a dominant standard for webdevelopment JavaScript is a key feature in how some of its more interesting aspects work
Node.js
In 2009, Ryan Dahl developed Node.js, which allows server-side applications to be written
in JavaScript It is based on the Google’s V8 engine and implements non-blocking inputand outputs in an event-driven environment This allows the creation of fast and powerfulreal-time web applications written exclusively in JavaScript It has also lead to manyapplications and JavaScript libraries that don’t use the browser at all Node JS has proven
Trang 38It certainly seems like JavaScript has a bright future As the web platform continues toevolve and mature and its usage grows beyond the browser, JavaScript is sure to remain acentral part of future developments
Trang 39A ninja needs very little to program JavaScript All one needs is a text editor and a webbrowser such as Firefox, Opera, Internet Explorer, Safari, or Chrome
JavaScript Version
We’ll be using version 5 of ECMAScript in this book and assume that you are using amodern browser (try to update to the latest version of whichever is your favorite) Youcan’t always rely on users to have the latest version, though, so we’ll also try to point outwhen some of the code will fail to work in older browsers
Text Editors
If you are using Windows, Notepad will work just fine If you find it a bit too basic, youmight want to try Notepad++, E Text Editor, UltraEdit, or Sublime Text
If you are using a Mac, options include the built-in TextEdit, Text Wrangler, TextMate, or
If you are using Linux, you’ll be fine with the built-in text editor (such as Gedit, Genie,Kate, Vim, or Emacs), or you could also use E Text Editor or Sublime Text
You can also consider an Integrated Development Environment (IDE) such as Eclipse,
Another interesting option is Brackets, which is free, cross-platform, and even written inJavaScript!
Browser Console
Nearly every browser can run JavaScript and most modern browsers now include aJavaScript console that can be used to run snippets of JavaScript code Here are someinstructions on how to launch a JavaScript console in some of the more popular browsers:
Trang 40Another option is to use the excellent JS Console website This allows you to enterJavaScript commands directly into the browser and see the results I have used thisconsole to run most of the code snippets in this book.