Introduction to JavaScript
Copyright © by Application Developers Training Company – www.learnnowonline.com
Objectives • Learn about the JavaScript language, its history, uses, and versions • Explore some of the tools available to develop and debug JavaScript code • See the anatomy of JavaScript, its core structural features
Copyright © by Application Developers Training Company – www.learnnowonline.com
Agenda • The JavaScript Language • Developing and Debugging JavaScript • The Anatomy of JavaScript
Copyright © by Application Developers Training Company – www.learnnowonline.com
The JavaScript Language • The programming language of the Web § Use with the DOM § Manipulate a page dynamically § Provide instant responses to users
• Browsers live on because of JavaScript • Most used programming language in the world § Closest thing we have to universal language
• Prototype-based interpreted scripting language § Has dynamic and functional characteristics § Weakly typed and supports OOP § Descendant of C, related to Java Copyright © by Application Developers Training Company – www.learnnowonline.com
A Brief History of JavaScript • Netscape’s Brendan Eich designed JavaScript § Mere 10 days § First named LiveScript § Shipped with version 2.0 of Netscape Navigator
• Sun wanted to kill LiveScript and make Java the language § Netscape changed name to appease Sun and ride Java’s wave of popularity § Also wanted a simpler programming model
• Browser wars heated up § Microsoft created JScript Copyright © by Application Developers Training Company – www.learnnowonline.com
The Good, Bad, and Ugly • JavaScript has both good and bad parts § Good: things of beauty and elegance that make JavaScript a marvelous language § Bad: sometimes nasty, fostering bad code
• Where do the bad parts come from? § Legacy design elements § Good intentions § Haste
• For the most part, you can ignore the bad parts
Copyright © by Application Developers Training Company – www.learnnowonline.com
Rise to Fame • Long denigrated as a flawed, toy language § Uncertain whether it would survive § Java was expected to replace it
• But then Ajax happened § Spawned the era of Web 2.0 § Greater interactivity, cooperating in a dialog to create content § As Ajax took hold, professional programmers took a fresh look at JavaScript and liked what they saw § Frameworks and libraries followed
• The future of JavaScript is bright and assured Copyright © by Application Developers Training Company – www.learnnowonline.com
ECMAScript: Standardized JavaScript • Netscape looked to standardize JavaScript • Ecma International § Originally the European Computer Manufacturers Association (ECMA) § Sun owned name, so needed a new one § Became ECMAScript by default
Copyright © by Application Developers Training Company – www.learnnowonline.com
ECMAScript Releases Version 1 2
Release Date June 1997 June 1998
3
December 1999
4
--
5
December 2009
5.1
June 2011
Major Changes Initial release. Primarily editorial changes to keep the specification aligned with the ISO/IEC 16262 international standard for ECMAScript. Added support for regular expressions, improved string handling, new control statements, exception handling, and various numeric output formatting, and more. Abandoned due to political differences and technical difficulties with the complexity of the language. Some features developed made it into version 5, others were deferred for future versions. Added Strict mode, clarified ambiguities, and implemented accommodations for real-world uses of implementations. Added getters and setters, support for JSON, and reflection on object properties. Released to align with the third edition of the international standard ISO/IEC 16262:2011.
Copyright Š by Application Developers Training Company – www.learnnowonline.com
State of ECMAScript • All modern browsers now use ECMAScript 3 • ECMAScript 5 slowly making its way into browsers § Default § Strict
• Use strict mode with “use strict” • <script> "use strict"; ... rest of JavaScript code </script> Copyright © by Application Developers Training Company – www.learnnowonline.com
Which Version Should You Use? • Options: § ECMAScript 3 § ECMAScript 5/Default § ECMAScript 5/Strict
• Choice governed by target browsers § ECMAScript 3 is safe today § ECMAScript 5 is coming § Use strict mode, since it is safest
• Take Douglas Crockford’s advice: § In the short term, stick to common elements of ECMAScript 3 and 5/Strict Copyright © by Application Developers Training Company – www.learnnowonline.com
The Name of the Language • JavaScript has had several names § Mocha and LiveScript are defunct § JavaScript, JScript, and ECMAScript are in current use
• Each is a particular thing § JavaScript is trademark of Oracle, used by Mozilla § JScript is the language of Internet Explorer § ECMAScript is the standard language
• Everyone uses JavaScript
Copyright © by Application Developers Training Company – www.learnnowonline.com
Language Versions • Many versions in many places JavaScript Version 1.0 1.1 1.2 1.3 1.5 1.6 1.7 1.8 1.8.1 1.8.2 1.8.5
Version Released March 1996 August 1996 June 1997 October 1998 November 2000 November 2005 October 2006 June 2008 June 2009 January 2010 March 2011
Equivalent to
ECMAScript 1 & 2 ECMAScript 3 ECMAScript for XML
ECMAScript 5
Netscape Navigator 2.0 3.0 4.0-4.05 4.06-4.7x 6.0
Mozilla Internet Google Firefox Explorer Chrome 3.0
1.0
4.0 5.5-8.0
1.0-10.0. 666
1.5 2.0 3.0 3.5 3.6 4
9, 10
Copyright © by Application Developers Training Company – www.learnnowonline.com
13.0+
JavaScript Across Browsers • Hardest thing about using JavaScript § Problem may be browser implementation of the DOM § Even JavaScript engines are different
• Strategies § Write standards-compliant code § Check the environment
• Writing to the environment means lots of code
Copyright © by Application Developers Training Company – www.learnnowonline.com
JavaScript May Not Be Available • Problems § Disabled § Not available in the browser § Accessibility issues
• Options § Degrade gracefully § Progressive enhancement
• Frameworks and libraries § Particularly for Ajax
Copyright © by Application Developers Training Company – www.learnnowonline.com
Agenda • The JavaScript Language • Developing and Debugging JavaScript • The Anatomy of JavaScript
Copyright © by Application Developers Training Company – www.learnnowonline.com
Developing and Debugging JavaScript • Huge numbers of tools you can use § Plainest of text editors to complex development tools § Commercial and open source § Expensive and free
• Major browsers have built-in tools and extensions § § § § §
Firefox: built-in tools and Firebug IE: built-in F12 tools and Fiddler2 Chrome: built-in Web development tools Opera: built-in DragonFly tools Safari: built-in developer tools Copyright © by Application Developers Training Company – www.learnnowonline.com
Which Browser to Use? • Any will generally work fine for development § Many tools are similar, with unique features § Tools available where you need to test sites
• Use Chrome in this course § Loads and runs noticeably faster § Implements emerging standards § Has an edge with developer tools
Copyright © by Application Developers Training Company – www.learnnowonline.com
Chrome Web Developer Tools • Built into every copy of the browser • Reach deep into the internals of a Web page and the browser itself • Improve with every new version of Chrome • Using the latest version § Stable channel § New release about every six weeks § Be on the bleeding edge with Developer or Beta channels
• Based on WebKit Web Inspector Copyright © by Application Developers Training Company – www.learnnowonline.com
Elements Panel • Displays the Web page that the browser renders § Explore its HTML, CSS styles, and DOM objects § Can make changes
• Powerful tools for fine-tuning appearance and solving layout and content problems
Copyright © by Application Developers Training Company – www.learnnowonline.com
Resources Panel • Lists all of the resources used by the page § § § § §
HTML page itself CSS stylesheet files JavaScript and other code files Cookies and various types of storage Caches
Copyright © by Application Developers Training Company – www.learnnowonline.com
Network Panel • Information about the resources the browser downloads for a page § Resources Panel: content and characteristics of the page resources § Network panel: focused on network resources needed to retrieve the page resources
• Waterfall diagram of network activities
Copyright © by Application Developers Training Company – www.learnnowonline.com
Scripts Panel • Powerful, in-browser script debugger • Rivals features of Web development environments
Copyright © by Application Developers Training Company – www.learnnowonline.com
Timeline Panel • Useful to diagnose and fix performance problems in JavaScript code § As well as other resources used by the page
• Profile records wealth of information § Only cover the highlights § Well worth taking time to explore this panel
Copyright © by Application Developers Training Company – www.learnnowonline.com
Profiles Panel • Profile both CPU and heap memory • Like Timeline, have to explicitly start and stop recording • Analyze events in the panel
Copyright © by Application Developers Training Company – www.learnnowonline.com
Audits Panel • Provides network utilization and performance information about a Web page § Based either on reloading or loaded state
• Similar in some ways to Yahoo!’s YSlow extension
Copyright © by Application Developers Training Company – www.learnnowonline.com
Console Panel • Scripts and Console panels together provide powerful tools for JavaScript code • Use Console to directly enter and execute JavaScript code • Can write to the Console from code
Copyright © by Application Developers Training Company – www.learnnowonline.com
JSLint • Invaluable tool while learning and even after you become an expert • Static code analysis tool § Insight into quality of your code § Written by Douglas Crockford § Available online and in command line versions
Copyright © by Application Developers Training Company – www.learnnowonline.com
Working with JavaScript • Initially going to focus on the language § § § §
Ignore how JavaScript interacts with a Web page But need a way to run code Will use a very simple Web page Use HTML 5 syntax and structure
Copyright © by Application Developers Training Company – www.learnnowonline.com
The HTML Script Element • Key to using JavaScript in a Web page • Two ways to use § Script embedded inline <script> console.log("Hello, Page!"); </script>
§ External JavaScript file <script src="jquery-1.7.1.js" />
• Optional type attribute can specify content § text/javascript
• Include as many script elements as you want Copyright © by Application Developers Training Company – www.learnnowonline.com
HTML Comments in Script Tag • You may see code like this: <script> <!— console.log("Hello, Page!"); //--> </script>
• Prevent older browsers from treating as page content • Such browsers are nearly extinct now, so no need to do this anymore Copyright © by Application Developers Training Company – www.learnnowonline.com
Agenda • The JavaScript Language • Developing and Debugging JavaScript • The Anatomy of JavaScript
Copyright © by Application Developers Training Company – www.learnnowonline.com
The Anatomy of JavaScript • Begin exploring the JavaScript language • Lexical structure § Set of elementary rules that guide how you write code § Low-level syntax details of JavaScript
Copyright © by Application Developers Training Company – www.learnnowonline.com
Case Sensitivity • JavaScript is case-sensitive • All of these are unique identifiers dateofbirth DateOfBirth dateOfBIRTH dAtEoFbIrTh DATEOFBIRTH
• Potential confusion: HTML is not case-sensitive § JavaScript has object and property names the same as HTML § Must be onclick in JavaScript, can be any casing in HTML Copyright © by Application Developers Training Company – www.learnnowonline.com
Identifiers • Name for anything you create in code § Variables, arrays, functions, labels, and objects
• Rules for naming identifiers § Consist of letters, underscores, digits, or dollar signs § First character can’t be a number § Cannot be a reserved word
• Valid identifiers § a, aaa, $birth, _birth, _$birth67, app$dev, x123$, birth_date
• Invalid identifiers § 23birth, *birth, Birth-date Copyright © by Application Developers Training Company – www.learnnowonline.com
Reserved Words • Keywords of the language • Depends on version of JavaScript you’re using • To be safe, avoid all reserved words from all versions abstract arguments boolean break byte case catch char class const continue debugger default
delete do double else enum eval export extends false final finally float for
function goto if implements import in instanceof int interface let long native new
null package private protected public return short static super switch synchronized this throw
throws transient true try typeof var void volatile while with yield
Copyright © by Application Developers Training Company – www.learnnowonline.com
Literals • Fixed value that appears in code § As opposed to a variable whose value can change
• Some literals of different types "Don Kiely" 'Don Kiely' 256 3.14159265 false null
// // // // // //
String literal using double quotes String literal using single quotes An integer number A floating point number A Boolean literal The absence of an object
Copyright © by Application Developers Training Company – www.learnnowonline.com
Semicolons • JavaScript uses semicolons (;) as statement terminator § Lets you break long statements on multiple lines § Interpreter combines everything at runtime
• To make easier for casual programmers, semicolons are largely optional § Provides automatic semicolon insertion § Mostly does the right thing § But there are cases where it fails
Copyright © by Application Developers Training Company – www.learnnowonline.com
Whitespace • In JavaScript, extra whitespace is irrelevant • Need spaces between identifiers and keywords • Line breaks are sometimes significant, but not often • Language ignores any extra leading indentations, line breaks, tabs, and spaces
Copyright © by Application Developers Training Company – www.learnnowonline.com
Comments • Commenting code is a universal best practice § Provides some level of documentation § Aids in maintenance
• Two types of comments § Single line: // § Block or multi-line: /* */
Copyright © by Application Developers Training Company – www.learnnowonline.com
Learning from Other Web Sites • Very helpful to explore real world examples § Both good and bad
• Browser needs access to code, so you can explore it for any site § Use your developer tools to explore
• But sites can minify code § Worse, can obfuscate it
• See JavaScriptResources.html in course sample files
Copyright © by Application Developers Training Company – www.learnnowonline.com
Learn More! • This is an excerpt from a larger course which you can access at: http://learnnowonline.com/
Copyright © by Application Developers Training Company – www.learnnowonline.com