javascript needn't hurt!

92
JavaScript Needn’t Hurt! Thomas Kjeldahl Nilsson [email protected] linkedin.com/in/thomaskjeldahlnilsson twitter.com/thomanil

Upload: thomas-kjeldahl-nilsson

Post on 20-Jan-2015

3.474 views

Category:

Technology


1 download

DESCRIPTION

My half-day JavaScript crash course. Download slides, notes, exercises, solutions, examples and tools from http://kjeldahlnilsson.net

TRANSCRIPT

Page 1: JavaScript Needn't Hurt!

JavaScript Needn’t Hurt!

Thomas Kjeldahl [email protected]

linkedin.com/in/thomaskjeldahlnilssontwitter.com/thomanil

Page 2: JavaScript Needn't Hurt!

Intro

Page 3: JavaScript Needn't Hurt!

Who Are You?Done any JavaScript?Dozen lines of code?

Hundreds? Thousands?

Page 4: JavaScript Needn't Hurt!

Who Am I?JavaScript enthusiast

Hundreds of hoursThousands lines of code

Not an expert!

Page 5: JavaScript Needn't Hurt!

What Are We Covering Today?

Language basicsHtml scripting

Good practicesTools

Page 6: JavaScript Needn't Hurt!

Practical Stuff

Page 7: JavaScript Needn't Hurt!

History Lesson

Page 8: JavaScript Needn't Hurt!
Page 9: JavaScript Needn't Hurt!

Brendan Eich

Page 10: JavaScript Needn't Hurt!

ECMAScript

Page 11: JavaScript Needn't Hurt!

A Note on ActionScript

Page 12: JavaScript Needn't Hurt!

What Rocks?Powerful, elegant, dynamic

Present & enabled for most usersNot confined to the browser

Small learning surface

Page 13: JavaScript Needn't Hurt!

What Sucks?Rushed out the door

Some bad language featuresCrossbrowser problems

Page 14: JavaScript Needn't Hurt!

Development Environment

Walkthrough

Page 15: JavaScript Needn't Hurt!

Language Basics

SyntaxTypes

VariablesObjects

Functions

Page 16: JavaScript Needn't Hurt!

Basic SyntaxSimilar to Java, C#

Operators, statementsif-else, while, for, try-catch-finally

Still in Kansas...

Page 17: JavaScript Needn't Hurt!

TypesStrings

NumbersBooleans

ObjectsArrays

Page 18: JavaScript Needn't Hurt!

Variable Declarations

var x = “foo”; // string

var x = 2; // number

var x = true; // boolean

var x = { }; // object

var x = [ ]; // array

Page 19: JavaScript Needn't Hurt!

Objects

Page 20: JavaScript Needn't Hurt!

Object CreationLiteral Form

var BasicProject = {

name : "Steria Workshop",

version : 1.2,

getName : function() {

return this.name;

}

};

Page 21: JavaScript Needn't Hurt!

Object CreationDynamic Form

var BasicProject = {};

BasicProject.name = "Steria Workshop";

BasicProject.version = 1.2;

BasicProject.getName = function() {

return this.name;

};

Page 22: JavaScript Needn't Hurt!

Objects as Maps(Associative Arrays)

var Person = { firstname:"John", lastname:"Smith" };

Person.firstname; // => "John" (Access using identifier)

Person["firstname"]; // => "John" (Access using variable name)

Page 23: JavaScript Needn't Hurt!

Arrays are Special Case of Object

var arr = []; // Always declared without size.

// Grows as needed.

arr[0] = true;

arr[3] = "john";

arr[300] = { description : "object!" };

arr[100]; // => Undefined

arr.length; // => 301

Page 24: JavaScript Needn't Hurt!

Arrays and ObjectsCan Be Deeply Nested

var OuterObject = {

innerArray : [

innerObject : {

deepestArray : [1,2,3]

}

]

};

Page 25: JavaScript Needn't Hurt!

JSON

{"firstName":"Gustav","lastName":"Adolf",

"roles":["King of Sweden","Terrible shipbuilder"],

"other":{"birth":"9.12.1594","death":"16.11.1632"}}

Page 26: JavaScript Needn't Hurt!

Kind Familiar Looking

{

"firstName" : "Gustav",

"lastName" : "Adolf",

"roles" : [

"King of Sweden",

"Terrible shipbuilder"

],

"other" : {

"birth" : "9.12.1594",

"death" : "16.11.1632"

}

}

Page 27: JavaScript Needn't Hurt!

JavaScriptObject Literal!

var EvaluatedObject = {

firstName : "Gustav",

lastName : "Adolf",

roles : [

"King of Sweden",

"Terrible shipbuilder"

],

other : {

birth : "9.12.1594",

death : "16.11.1632"

}

};

Page 28: JavaScript Needn't Hurt!

Inheritance

Page 29: JavaScript Needn't Hurt!

Prototypal Inheritance (Simplified)

var Employee = {name : "CEO Jack", company : "ACME Inc."};

var Janitor = Object.create(Employee);

// Janitor now looks and behaves just like its prototype, Employee

Janitor.company // => "ACME Inc.", falls back to prototype.company

Janitor.name = "Janitor Tim"; // Override name

Janitor.tools = ["broom", "bucket"]; // Define member variable only on child

Employee.name = "CEO Jane"; // Change name of prototype

Janitor.name; // => Still "Janitor Tim". Overriden members unaffected by prototype changes

Page 30: JavaScript Needn't Hurt!

Functions

Page 31: JavaScript Needn't Hurt!

Simple Function Definition

function add(a, b) {

return a + b;

}

Page 32: JavaScript Needn't Hurt!

That's Just a Way of Saying:

var add = function(a, b) {

return a + b;

};

// Use this consistently

// Helps you remember:

// Functions are just variables!

Page 33: JavaScript Needn't Hurt!

An AnonymousFunction...

function(element) {

// Do something with element

}

Page 34: JavaScript Needn't Hurt!

...Can Be SentTo Another Function

each(collection, function(element) {

// Do something with current element

});

Page 35: JavaScript Needn't Hurt!

Example:Event Handler

button.onClick(function(element) {

alert(«You clicked me!»);

});

Page 36: JavaScript Needn't Hurt!

Sharp EdgesGlobal variablesNo block scope

Semicolon insertion== operator

Page 37: JavaScript Needn't Hurt!

Properly ScopedVariable

var getSmallNumber = function(){

var smallNumber = 42; // Note use of var keyword

return smallNumber;

};

Page 38: JavaScript Needn't Hurt!

Sloppy,Global Variable

var getSmallNumber = function(){

smallNumber = 42;

return smallNumber;

};

// Missing var prefix = smallNumber gets global scope

// Becomes available for all code

// Sticks around and pollutes namespace

Page 39: JavaScript Needn't Hurt!

No Block Scope

var x = 1;

if (true) {

var x = 123;

}

// x => 123

Page 40: JavaScript Needn't Hurt!

Semicolon insertion

Don't force the browser to guess!

Page 41: JavaScript Needn't Hurt!

Example

a = b + c

(d + e).print()

becomes...

a = b + c(d + e).print();

Page 42: JavaScript Needn't Hurt!

== vs ===

Page 43: JavaScript Needn't Hurt!

Quiz

'' == '0' // true or false?

0 == '' // true or false?

0 == '0' // true or false?

false == 'false' // true or false?

false == '0' // true or false?

false == undefined // true or false?

false == null // true or false?

null == undefined // true or false?

' \t\r\n ' == 0 // true or false?

Page 44: JavaScript Needn't Hurt!

How ManyDid You Get?

'' == '0' // false

0 == '' // true

0 == '0' // true

false == 'false' // false

false == '0' // true

false == undefined // false

false == null // false

null == undefined // true

' \t\r\n ' == 0 // true

// Why? Type coercion on right operand, that's why.

Page 45: JavaScript Needn't Hurt!

Instead, Use ===(And !==)

'' === '0' // false

0 === '' // false

0 === '0' // false

false === 'false' // false

false === '0' // false

false === undefined // false

false === null // false

null === undefined // false

' \t\r\n ' === 0 // false

Page 46: JavaScript Needn't Hurt!

Advanced StuffClosuresModules

Memoization

Page 47: JavaScript Needn't Hurt!

ClientsideFirebugjQuery

Page 48: JavaScript Needn't Hurt!

FirebugDemo

Page 49: JavaScript Needn't Hurt!

The DOM

Page 50: JavaScript Needn't Hurt!
Page 51: JavaScript Needn't Hurt!

<TABLE> <TBODY> <TR> <TD>Shady Grove</TD> <TD>Aeolian</TD> </TR> <TR> <TD>Over the River, Charlie</TD> <TD>Dorian</TD> </TR> </TBODY> </TABLE>

Page 52: JavaScript Needn't Hurt!
Page 53: JavaScript Needn't Hurt!

DOM ScriptingBasics

x.getElementById(id) ; // get the element with a specified id

x.getElementsByTagName(name); // get all elements with a // specified tag name

x.appendChild(node); // insert a child node to x

x.removeChild(node), // remove a child node from x

x.innerHTML = «<p>New text</p>»; // fill element with html or text

Page 54: JavaScript Needn't Hurt!

Live Example

Page 55: JavaScript Needn't Hurt!

DOM Api:Crossbrowser Headache

http://www.quirksmode.org

Page 56: JavaScript Needn't Hurt!

So Use a Framework!

Page 57: JavaScript Needn't Hurt!

jQuery

Page 58: JavaScript Needn't Hurt!

Instant Win:CrossbrowserNon-verbose

Traverse DOMManipulate DOM

Page 59: JavaScript Needn't Hurt!

Lots of Other Stuff, Too

Server communicationUI widgets and effects

each(), map(), etcJSON parsing

+++

Page 60: JavaScript Needn't Hurt!

jQuery Function

$() // Short form

jQuery() // Long form

Page 61: JavaScript Needn't Hurt!

Find Stuff

$(“p”); // Find all paragraphs

$(“#shoppingList”); // Find element with id 'shoppingList'

$(“.shoppingListItem”); // Find elements with class 'shoppingListItem'

$(“:text”); // Find all text elements

$(“:visible”); // Find only visible elements

Page 62: JavaScript Needn't Hurt!

$() Wraps and Returns Matching Element(s)

Page 63: JavaScript Needn't Hurt!

Manipulate MatchedDOM Elements

$(“p”).css(”color”, ”green”); // Set color on all paragraph elements

$(“p”).hide(); // Hide all paragraphs

// Make all input buttons react to mouse clicks

$(“input”).click(function(){ alert(”You clicked this button!”); });

Page 64: JavaScript Needn't Hurt!

ChainingEvery API call returns jQuery object

So we can chain function calls together“Fluent API”

Page 65: JavaScript Needn't Hurt!

Chaining Example

// Set color on all paragraph elements, then hide them all

$(“p”).css(”color”, ”green”).hide();

Page 66: JavaScript Needn't Hurt!

Live Example

Page 67: JavaScript Needn't Hurt!

Prepared Example

Page 68: JavaScript Needn't Hurt!

Caution!Use frameworks as neededBut don't depend on them!

JavaScript != jQuery

Page 69: JavaScript Needn't Hurt!

Good PracticesjsLint

Automated testingUnobtrusive JavaScript

Page 70: JavaScript Needn't Hurt!

JsLintDemo

Page 71: JavaScript Needn't Hurt!

Automated Testing

YUI Test demo

Page 72: JavaScript Needn't Hurt!

Unobtrusive JavaScript

Structure vs behaviorSeparate js files

Event handler setupNamespaces

Universal Access

Page 73: JavaScript Needn't Hurt!
Page 74: JavaScript Needn't Hurt!
Page 75: JavaScript Needn't Hurt!
Page 76: JavaScript Needn't Hurt!
Page 77: JavaScript Needn't Hurt!
Page 78: JavaScript Needn't Hurt!

Namespace Hygiene

All your code within single object

Page 79: JavaScript Needn't Hurt!

Universal Access

Can all your users use your site?Users without JS?

Blind users with screen readers?Use progressive enhancement

Page 80: JavaScript Needn't Hurt!

Crossbrowser Dev Process

Frameworks > raw DOMTest early, test often

Clean, disciplined code

Page 81: JavaScript Needn't Hurt!

Let’s Code!Exercises

Page 82: JavaScript Needn't Hurt!

Wrap-up

Page 83: JavaScript Needn't Hurt!

What Did We Cover Today?

Language basicsHtml scripting

Good practicesTools

Page 84: JavaScript Needn't Hurt!

What´s Missing?Server Communication

PerformanceSecurity

Practice practice practice!

Page 85: JavaScript Needn't Hurt!

References & Further Studies

Page 86: JavaScript Needn't Hurt!
Page 87: JavaScript Needn't Hurt!
Page 88: JavaScript Needn't Hurt!

Web Resourceshttp://javascript.crockford.comhttp://cjohansen.no/javascript

http://developer.yahoo.com/yui/theaterhttp://ajaxian.com

Page 89: JavaScript Needn't Hurt!

Best Way to Learn:

Start Building!

http://ajaxian.com/archives/writing-a-javascript-tetris-lessons-learned-from-a-ruby-chap

Page 90: JavaScript Needn't Hurt!

DownloadThis Workshop

http://kjeldahlnilsson.net/jsnh.zipSlides, lecture notes, exercises

Creative Commons licenseUse and distribute freely...

...or have me present it for you on-site :)

Page 91: JavaScript Needn't Hurt!

Q&A Discussion

Page 92: JavaScript Needn't Hurt!

Contact [email protected]

linkedin.com/in/thomaskjeldahlnilssontwitter.com/thomanil