12
JavaScript Literacy Intermediate Language Features for Reading and Understanding JavaScript David Jacobs @MetaThis

JavaScript Literacy

Embed Size (px)

DESCRIPTION

Intermediate Language Features for Reading and Understanding JavaScript

Citation preview

Page 1: JavaScript Literacy

JavaScript LiteracyIntermediate Language Features

for Reading and Understanding JavaScript

David Jacobs@MetaThis

Page 2: JavaScript Literacy

Object Literal Notation

// create a person objectvar person = {};person.firstName = "Joe";person.lastName = "Jones";person.address = {};person.address.street = "123

main";person.address.zip = "12345";person.address.state = "MO";

// same thing in object literal notationvar person = { firstName: "Joe", lastName: "Jones", address: { street: "123 main", zip: "12345", state: "MO" }};

Page 3: JavaScript Literacy

Object Literals with Functions// can include functionsvar person = { firstName: "Joe", lastName: "Jones", address: { street: "123 main", zip: "12345", state: "MO" }, getFullName: function() { return this.firstName + " " + this.lastName; }};

Inline function

Page 4: JavaScript Literacy

Object Literals - JSONJSON is a subset of Object Literal notation• Requires property names to be in quotes• Functions are not allowed• Special characters must be

escaped/encoded

Other than these restrictions, you cansimply think of JSON as a JavaScript object• All valid JSON is a valid Object Literal

var person = { "firstName ": "Joe", "lastName ": "Jones", "address": { "street": "123 main", "zip:": "12345", "state ": "MO" } getFullName: function() { return … }};

Page 5: JavaScript Literacy

Argumentsfunction doSomething(a, b, c) { // something}

// arguments are optionaldoSomething(); //this is valid!

// can pass extra argumentsdoSomething("apple", “banana", "cat", "wtf"); //this is also valid!

// regardless of declared parameters, functions have access // to all arguments through a special arguments arrayfunction doSomething() { return arguments[3]; //returns "wtf"}

Page 6: JavaScript Literacy

Object Literals as Arguments

JavaScript Idiom for Optional Named Parameters• Functions often have an optional “options” or “settings”

parameter

jQuery.ajax( url, [settings] )

• Object Literals are often used as constructors, providing or overriding defaults

jQuery.ajax( {url: "test.html", data: myObject, success: alert("success")} )

Page 7: JavaScript Literacy

Arrays• The Array prototype contains methods specific to arrays, but as a

data structure…– Arrays are essentially just object literals with an implicit number as the

property name– Which generalizes to a universal property:value pattern for all objects

(and JSON data)– Which enables a universal data access pattern of object[property]

var array = ["first","second", "third"];var object = {0: "first", 1: "second", 2: "third"};

array[1] //returns "second"object[1] //returns "second“

Don’t take this point too literally…but it may help you better understand JavaScript data structures.

Page 8: JavaScript Literacy

|| and &&

You know• || is a boolean Or• && is a boolean And

Do you know?• Expressions using them can return a non-boolean value• This is useful

// if userInput is null or an empty string, then the Or case // is evaluated and returned as a valuevar name = userInput || "Bob";

// conditional execution – validate() is only called if there’s a valuevar valid = userInput && validate(userInput);

Page 9: JavaScript Literacy

Functions

• Functions are objects• Functions are values– Can be assigned to a variable– Can be passed to another function as an argument– Can be returned by a function

• Functions are the building blocks of scope– A function created inside a function is a nested scope– The outer scope is available to the inner scope– The inner scope is not available to the outer

Page 10: JavaScript Literacy

Function Pointers

What is the $ in jQuery?

// in this example, $ is a variable that points to a functionvar $ = function (id) { return document.getElementById(id); };

// this is a function call on the $ variable, setting the onClick handler // on the DOM element returned by the function$('yourDiv').onClick = function (event) { //do something };

Page 11: JavaScript Literacy

Callbacks

• A callback is just a function that is passed to another function, typically with the intent of it being called later (“called back”)

TIP: Callbacks are often easier to understand if you use function pointers (assigning a function to a variable) instead of creating an anonymous function on-the-spot.

Page 12: JavaScript Literacy

Higher Order Functions• A higher order function is a function that takes or returns a function• All asynchronous callback-style function calls involve higher order

functions• They are used nearly everywhere in JavaScript

– AJAX calls, event handling, Node.js, etc

• A better understanding of functional programming will improve your JavaScript code and your programming skills

Learn More about Functional JavaScriptArticle: http://www.hunlock.com/blogs/Functional_JavascriptBook: JavaScript Patterns by Stoyan Stefanov

Underscore.js An excellent utility library for functional programming in JavaScript:http://documentcloud.github.com/underscore /