INTRO TO JAVASCRIPT
Don't Complain About It, Embrace It!
Ben Centra
blcentra@gmail.com
@TheBenCentra
What is Javascript?
- A C-style programming language that...
- ...is prototype-based
- ...is interpreted
- ...is dynamically typed
-
...has first-class functions
- Primarily for client-side web development
- User Interation
- DOM Manipulation
- Asynchronous Communication
History of javascript
- First released in '95 for Netscape Navigator 2.0
- Implemented by Microsoft for IE3 in '96 as "JScript"
- ECMAScript standard developed in '97
- Hated by developers ever since*
Tidbit: The first server-side implementation of JavaScript was released in '94 for Netscape Enterprise Server
* Citation Needed
The Basics
Hopefully this won't take long.
Using Javascript
- In a separate file included in an HTML document
<script type="text/javascript" src="script.js"></script>
- In a <script> block in an HTML document
<script type="text/javascript">
alert("Hello, World!");
</script>
- In an attribute of a DOM element
<button onclick="alert('Hello, World!');">Click Me</button>
Variables & Types
- Variables are dynamically typed
- "Primitive" Data types:
- Numbers (ex - var x = 5)
- Strings (ex - var s = "Hello")
- Booleans (ex - var b = true)
- Null (ex - var x = null)
- Undefined
Variables & Types
- Additional Data Types (Objects)
- Objects (ex - var o = {})
- Arrays (ex - var a = [1,2,3])
-
RegExp (ex - var r = /pattern/)
- Functions
- Maths
- Dates
- "Everything" is an object in JavaScript
Control Structures
- The Usual:
- if, else if, else
-
switch (<var>) { case 1: ... default: }
- while (<condition>) { }
- for (var x = 0; x < y; x++) { }
- The Unusual:
- for (<var> in <object>) { }
- Array.forEach(<callback> [, <this> ]);*
* IE9 or higher
Using Arrays
// Instantiate an array
var array = new Array("One", "Two", "Three");
var array = ["One", "Two", "Three"];
// Add things to the array
array.push("Four"); // End
array.unshift("Zero"); // Beginning
array.splice(2, 0, "Two Point Five"); // Anywhere
// Remove things from the array
array.pop(); // End
array.shift(); // Beginning
array.splice(2, 1); // Anywhere
Using Arrays
// Get array length
console.log(array.length);
// Combine array into a string
console.log(array.join());
// Find an element in the array
console.log(array.indexOf("Three"));
// Combine multiple arrays
array.concat(array2);
// ...and some other stuff
Using Objects
- Objects have properties and methods
// Declare my car object
var car = new Object();
// Properties of my car
car['make'] = "Toyota"; // Use dictionary notation
car.model = "Camry"; // Or dot notation
car.year = 2009; // Use whatever types you want
// Methods of my car (properties that are functions)
car.drive = function() {
console.log("I am driving my "+this.make+" "+this.model);
}
functions
The reason why most programmers hate JavaScript.
Functions
- "Modular unit of execution"
Functions are "first-class" objects that can be...
-
...created via literals
-
...assigned to variables, array entries, properties
-
...passed as arguments to functions
-
...returned as values from a function
- ...given properties, dynamically created/assigned
- Functions are special in that they can be invoked
Function Declaration
- Use the function keyword
- A valid (but optional) name
- Parameters, comma separated, within ()'s
- Body, JavaScript statements within {}'s
// Here is a plain ol' named function with one argument
function addFiveToIt(arg1) {
// Do something, maybe even return a value
return arg1 + 5;
}
Function Parameters
- # Parameters == # Arguments
-
Everything goes as planned
- # Parameters > # Arguments
-
Missing parameters set to "undefined"
- # Parameters < # Arguments
-
Extra arguments still found in arguments "array"
Function Scope
- Scopes declared by functions, not by blocks!
- Variables are in scope from declaration until the
end of the function in which they are declared
- Named functions are in scope within the entire function
in which they are declared (also called "hoisting")
- "Global" context acts as a big function encompassing all the code
Quiz Time!
var x = 0;
function outer() {
var a = 1;
function inner() {
var b = 2;
if (a == 1) {
var c = 3;
}
}
}
- Where can I call outer()? inner()?
- What are the scopes of x, a, b, and c?
Using Callbacks
Pass a function as a parameter to another function!
// Pass a reference to an existing function
document.addEventListener("DOMContentLoaded", readyFunction);
// Use an anonymous function
document.addEventListener("DOMContentLoaded", function() {
// Function body goes here
});
CHOOSE YOUR PATH
If you're done with functions, skip ahead.
If not, let's keep trudging along.
Function Invocation
- As a function (straightforward)
- As a method, tie invocation to an object
- As a constructor, create a new object
- Via its apply() or call() methods
Each method affects function context ("this")
Invocation as a function
Use () operator on an expression that references a function.
function namedFunction() { }
namedFunction();
var anotherFunction = function() { }
anotherFunction();
this refers to the global context (window)
Invocation as a method
Use () operator on a property of an object that is a function.
var car = {};
car.topSpeed = 100;
car.drive = function() { console.log("I'm driving at "+this.topSpeed); }
car.drive();
this refers to the object to which the method belongs
Invocation as a Constructor
Use the new keyword on a function to set up a new object.
function Car(make, model) {
this.make = make;
this.model = model;
}
var car = new Car("Toyota", "Camry");
this refers to the new object being created.
Apply() and Call()
Two methods of functions, allow you to make the function context whatever you want.
var subject = {};
function action() {
console.log(arguments);
this.affect = arguments[0];
}
action.apply(subject, [1,2,3]);
action.call(subject, 4, 5, 6);
Quiz Time!
var horse = new Horse("Jimmy");
horse.gallop();
listAllHorses(stable);
bet.call(horse, 100);
- Identify the different types of function invocation
used above
DOM Manipulation
The reason why ALL programmers hate JavaScript.
What is the 'dom'?
- Document Object Model
- Standard way to represent HTML/XML documents
- Organized as a tree of all elements
- Interact with the DOM through an API
Querying the dom
// Select an element by ID
var container = document.getElementById("container");
// Select elements by class name
var bolds = document.getElementsByClassName("strong");
// Select elements by tag name
var divs = document.getElementsByTagName("div");
// New-fangled querying using CSS Selectors!
var container = document.querySelector("#container");
var bolds = document.querySelectorAll(".strong");
var bolds = container.querySelectorAll(".strong");
creating elements
// Create a new element and give it some content
var div = document.createElement("div");
var content = document.createTextNode("Lorem ipsum");
div.appendChild(content);
// Append the element to the document
document.appendChild(div);
// Append the element to some other element
var container = document.getElementById("container");
container.appendChild(div);
updating elements
// Select an element
var input = document.createElement("input");
// Set some attributes
input.setAttribute("type", "text");
input.setAttribute("class", "textfield");
input.setAttribute("onchange", "updateValue(this.value)");
// Get some attributes
input.getAttribute("class");
// Delete an element
input.parentNode.removeChild(input);
Event Handling
User Interactions, Yeah!
EVent Model
- When something happens, an event is triggered
- Listen for events on DOM elements
- Write functions to handle events
Mouse Events
- Handle user input from a mouse
- Common events:
- onclick
- onmousedown
- onmouseover
- onmouseup
- onmouseout
Example - Mouse Event
<!-- Do it with HTML attributes -->
<button onclick="doSomething();">Click Me!</button>
<script>
// Handler from HTML example
function doSomething() { console.log("AAA"); }
// Or do it with JavaScript
var button = document.querySelectorAll("button")[0];
button.onmouseover = function() { console.log("BBB"); }
</script>
Keyboard Events
- Handle user input from a keyboard
- Common events:
- onkeypress
- onkeydown
- onkeyup
Example - Keyboard Event
<!-- Do it with HTML attributes -->
<input type="text" onkeyup="displayText(this.value)"/>
<script>
// Handler from HTML example
function displayText(text) { console.log(text) }
// Or do it with JavaScript
var input = document.querySelector("input")[0];
input.onkeypress = function(e) { console.log(e.keyCode); }
</script>
Frame/Object Events
- Handle changes in the <body>, the window, etc
- Common events:
- onload
- onunload
- onscroll
- onresize
Example - Frame Events
<!-- Do it with HTML attributes -->
<body onload="loadData()">...</body>
<script>
// Handler from HTML example
function loadData() { /* AJAX or something */ }
// Or do it with JavaScript
window.onload = loadData;
</script>
Form Events
- Handling events in form fields (<input>, etc)
- Common events:
- onblur
- onfocus
- onchange
- onselect
- onsubmit
- onreset
Example - Form Events
<!-- Do it with HTML attributes -->
<form>
<input type="text" onchange="updateValue(this.value)"/>
</form>
<script>
// Handler from HTML example
function updateValue(val) { globalVal = val; }
// Or just do it with JavaScript
var form = document.querySelectorAll("form")[0];
form.onsubmit = function () { /* AJAX or something */ }
</script>
AJAX Requests
Get yourself into that Web 2.0 hotness!
WHat Is 'AJAX'?
- Asynchronous JavaScript and XML
- Use to request data from a server-side source
- Files (XML, JSON, text, etc)
- Database
- Uses the JavaScript XMLHttpRequest object
- Standardized in 2006 by W3C
Initialize the request object
// Create the request object
var xmlhttp;
// Feature detection for real browsers
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
// Fake browsers (IE6 and below)
else {
xmlhttp = ActiveXObject("Microsoft.XMLHTTP");
}
Handle the Response
xmlhttp.onreadystatechange = function() {
// Only act on a successful response
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// Do Something
console.log(xmlhttp.responseText);
}
}
Make The Request
// Make a GET request
xmlhttp.open("GET", "data_source.php", true);
xmlhttp.send("param=value¶m2=value2");
// Make a POST request (i.e. submit a form)
xmlhttp.open("POST", "data_source.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("data="+formField.value);
Object-oriented javascript
That's right, I said it.
Functions as Constructors
- Declare your instance variables in the function body
- These things will only apply to the object created
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
this.speed = 0;
}
// Create an instance of Car
var myCar = new Car("Subaru", "Outback", 2006);
Object Prototypes
- All objects of a type share a common prototype
- Define all shared values/methods there
Car.prototype = {
drive:function() { ... }
speedUp:function(spd) { this.speed += spd; },
slowDown:function(spd) { this.speed -= spd; },
maxSpeed: 100,
minSpeed: 0
}
var carA = new Car("Subaru", "Outback", 2006);
var carB = new Car("Chevrolet", "Corvette", 1976);
(carA.maxSpeed == carB.maxSpeed) ? console.log(true) : console.log(false);
Extending Prototypes
- Object.create() will do the trick
- Creates a new object with the specified prototype
// Create a subclass of Car
function BetterCar (make, model, year, newProp) {
this.newProp = newProp
Car.call(this, make, model, year); // Call Car constructor
}
// Make sure BetterCar extends Car
BetterCar.prototype = Object.create(Car.prototype);
// Define some new stuff
BetterCar.prototype = {
fly: function() {
console.log("I'M FLYING");
}
}
OTHER USEFUL THINGS
It's Dangerous To Go Alone. Take These!
LIBRARIES
- jQuery
- Prototype
-
YUI
- MooTools
- DOJO
- Script.aculo.us
- Angular.js
- Backbone.js
- Ember.js
DOCUMENTATION
- Don't be afraid to look things up!
- Google
- StackOverflow
- W3Schools.com
- MDN (Mozilla Developer Network)
QUESTIONS?
Don't be a stranger.
Thanks for Listening!
Ben Centra
blcentra@gmail.com
@TheBenCentra
bencentra.com