JavaScript & jQuery
WET CodeFest 2.0 pre-session
@patheard / PWGSC
Overview
- JavaScript
- jQuery
- Debugging
- Performance
- WET
10,000 Foot View
- Untyped, interpreted language
- Well suited for object-oriented programming
- Uses prototypal inheritance
- Bumpy learning curve
Types
-
Two types
primitive and object
-
Primitive
Number, string, boolean, null and undefined
-
Object
Built-in (arrays, functions, etc) and custom
Primitives
- Immutable
-
Auto-type conversion
- Truthy and falsey values
// Following evaluate to false
undefined
null
0
-0
NaN
""
Objects
- Mutable
- Collection of named properties
- Properties can be primitives, objects or functions
var car = {
type: "k-car",
cheap: true,
wheels: 4,
getSpeed: function () {
return 60;
} };
Variables
- Declare with var keyword
- Dynamically typed
// i has a value of undefined
var i;
// i, j and k are undefined
var i, j, k;
// i, j and k are defined
var i = 1, j = "foo", k = false;
Variable Scope
-
Function Scope
Available to their function and nested functions -
Scope Chain
Local takes precedence
var scope = "global";
function getGlobal () {
return scope;
}
function getLocal () {
var scope = "local";
return scope;
}
console.log(getGlobal()); // "global"
console.log(getLocal()); // "local"
Variable Hoisting
- Variables are visible throughout function body
-
Define all variables at the top
var scope = "global";
function outputScope () {
console.log(scope); // undefined
var scope = "local";
console.log(scope); // "local"
}
outputScope();
Functions
- Declare with function keyword
- Re-usable chunks of code
- Functions define parameters and return value
- Functions are objects
// function that takes 2 parameters
function multiply (a, b) {
return a * b;
}
// calling the function with 2 arguments
multiply(2, 3); // 6
multiply.call({}, 4, 5); // 20
Using Functions
- Assigning to variables
- Properties of objects (methods)
- Anonymous (event handlers, timers)
- Constructors (new keyword)
var hello = function () {
return "Hello World";
};
var me = {
feeling: function (say) {
return "Feeling " + say;
}
};
Closures
- Special object
Consists of a function and the environment the function
was created in - Environment holds all variables that are in scope
when the closure is created
function sayHello(name) { var phrase = "Howdy " + name;
var called = 0;
return function(emoticon) {
return phrase + " " + emoticon + " " + (++called);
}; }
var pat = sayHello("Pat");
console.log(pat(":)")); // "Howdy Pat :) 1"
console.log(pat(":/")); // "Howdy Pat :/ 2"
Operators
- Used for assignment, comparison, arithmetic
and logical operations
= // assignment
==, != // equality, inequality
===, !== // strict equality, inequality (type must match)
<, <=, >=, > // greater and less than
+, -, *, / // arithmetic operations and string concat
++, -- // pre/post increment and decrement
+=, *=, -=, /= // arithmetic and assignment
% // module (remainder)
&&, ||, ! // logical AND, OR, NOT
?: // conditional operator (ternary operator)
Program Flow
-
Conditionals
if, else if, switch
-
Loops
while, do/while, for
-
Jumps
break, continue
Conditionals
if (answer === 42) { // Do something fancy
} else {
// Do something less fancy
}
switch(n) {
case 1:
// logic for n == 1
break;
case 2:
// logic for n == 2
break;
default:
// logic if no matching case
break; }
Loops
var count = 0; while (count++ < 10) { // loop 10 times }
do {
// loop 11 times
} while (count++ < 10);
for (var i = 0, l = a.length; i < l; i++) {
console.log(a[i]); // loop over an array
}
for (var p in o) {
console.log(p + ": " + o[p]); // loop over object properties
}
Jumps
var count = 0;
while (count++ < 10) {
if (count === 8) {
break; // jumps out of the loop
} else if (count === 3) {
continue; // jumps to next iteration of the loop
}
console.log(count);
}
Objects
- Fundamental data type of JavaScript
- Unordered collection of named properties
- Dynamically add/delete properties
-
Inherits properties from another object,
called its prototype
var obj = {
prop1 : "foo",
prop2 : "bar",
someMethod : function () {
return this.prop1 + this.prop2;
}
};
obj.someMethod();
Creating Objects
- Object literal notation
- Constructor and new keyword
- Object.create
Constructors and NEW
function Shape(x, y) {
this.x = x;
this.y = y;
this.getArea = function () {
return this.x * this.y;
}
}
var s = new Shape(5, 5);
s.getArea();
Object.create
- ECMAScript 5 method
-
Two arguments
1. Prototype to inherit from
2. Additional properties (optional)
// me inherits age and height properties
var me = Object.create({age: 35, height: 180});
// customDate inherits Date properties/methods
var customDate = Object.create(Date.prototype, {
someProp: {
value: "foo"
}
});
Prototype
function Shape(x, y) {
this.x = x;
this.y = y;
}
Shape.prototype = {
getArea: function () {
return this.x * this.y;
}
};
function Rectangle(x, y) {
Shape.call(this, x, y);
}
Rectangle.prototype = Object.create(Shape.prototype);
var r = new Rectangle(10, 5);
r.getArea();
THIS
- Reference to an object
-
Global context
Refers to global object (window)
-
Function context
Depends on how function is called
-
Constructor or Object method
Refers to the object
Properties
- Use dot or square brackets
- Square brackets allow for dynamic
property access
var o = {
x: 1
};
o.x; // 1
o['x']; // 1
var prop = 'x';
o[prop]; // 1
Arrays
-
Ordered collection of values
- Elements are untyped
- Use the .length property to iterate
var a = [1, 2, 3];
a.push(4); // Add an element to the end
a.pop(); // Remove the last element
var b = new Array();
b["cat"] = "meow";
b.dog = "woof";
for (var i = 0, l = a.length; i < l; i++) {
console.log(a[i]);
}
jQuery
-
Simplifies CodeDOM traversal/manipulationEvent handling
Animation
AJAX - Smooths out cross-browser issues
-
API: api.jquery.com
jQuery Objects
- Core element you work with
- Reference to DOM element(s)
- Created with $() function
// CSS selectors
var $h1 = $('h1'),
$notes = $('p.notes'),
$firstNote = $notes.filter(':first-child');
// DOM elements
var p = document.getElementById('foo'),
$p = $(p); // or even easier, $('#foo')
CSS Classes & Styles
-
Update styles
.css()
-
Update classes
.add/remove/toggleClass()
var $notes = $('#content > .notes');
$notes.css('background-color', 'red');
$notes.css({
opacity: .5,
fontSize: '1em'
});
$notes.addClass('big').removeClass('red');
$notes.toggleClass('big');
Attributes and Properties
-
Attributes
attr()
-
Properties
prop() - use for boolean attributes and properties
$('a').attr('href', 'http://google.ca');
$('input[type="checkbox"]').prop('checked', true);
Animation
- Animates between current and
specified properties - Use CSS animation instead (if possible)
var $notes = $('.notes');
$notes.animate({height: 100}, 500, function () {
console.log('finished animation!');
});
.notes {
height: 50px;
transition: height 1s ease-in;
}
.notes.taller {
height: 100px;
}
Events
-
React to something
"something" can be custom or predefined - Event handlers are bound to an object
- When the object detects an event, the handler
is executed
EVent Handlers
- Use the .on() and .off() methods
- Trigger with .trigger()
$('p').on('click', function() {
$(this).text('clicked');
});
$('p').trigger('click');
var $p = $('p');
$p.off('click').on('click', function(event) {
$p.text('clicked');
event.stopPropagation(); // stops the event from bubbling
});
$p.click();
Traversal
-
Move through the DOMUpparent(), parents(), closest()
- Down
children(), find()
$('p').parent();
$('p').parents('div');
$('p').children();
$('p').filter('.foo').find('strong');
Manipulation
- Modify the DOM
-
Add
.before(), .after(), .append(), .prepend()
-
Remove
.detach(), .remove(), .empty()
Debugging
- Chrome DevTools
- Firefox with Firebug
- IE Developer Tools
Performance
- Use native JavaScript
- Cache variables for reuse
- Update the DOM sparingly and apply
changes in one shot - Change CSS classes, not styles
- Use CSS animations
-
TEST
jsperf.com or home grown:
var t = new Date().getTime();
// Do some stuff
console.log(new Date().getTime() - t);
WET
-
pe-ap.js & theme.js
Core
-
Polyfills, plugins & dependencies
Workers
-
jQuery & jQuery Mobile
Libraries
-
i18n/en-min.js
Localization
Questions?
JavaScript & jQuery
By Pat Heard
JavaScript & jQuery
Pre-session for WET CodeFest 2.0
- 1,599