JavaScript - The weird parts

Presenter Notes

Our Presenters

David Luecke

Eric Kryski

Presentation:

Codecast:

Presenter Notes

Our Sponsors

Assembly Co-working Space

Assembly

PetroFeed

PetroFeed

Presenter Notes

Our Sponsors

Village Brewery

Village Brewery

Presenter Notes

You know?

  • Object Oriented Programming basics (classes, objects, inheritance)
  • JavaScript language basics
    • Operators [], &&, ==, ||
    • Arrays and Objects [].push, {}
    • Functions var fn = function(param1, param2) {}
  • Some jQuery
    • Selectors tagname, #myId, .class
    • Event handlers $('selector').click(function() { alert('clicked'); })

Presenter Notes

Welcome to the weird side

  • functions
  • truthy and falsyness
  • Equality
  • Scope
  • this
  • Prototypes
  • Asynchronous programming
  • ECMAScript 5 and 6

Presenter Notes

Warm up...

Accessing object properties

var person = {
  name: 'david',
  '&weird property': 'YYCJS'
}

person.name // -> David
person['name'] // -> David
person["name"] // -> David
person['&weird property'] // -> YYCJS

// ERROR
person.&weird property

Presenter Notes

Functions and arguments

Functions are treated just like any other variable:

var myFunction = function(arg) {

}
// the same as
function myFunction(arg) {

}

arguments is a special array-like variable that contains all parameters passed to the function call:

function sum() {
    var sum = 0;
    for(var i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

sum(1, 2, 3, 4); // -> 10

Presenter Notes

Truthy- and falsyness

Truthyness

var person = { name: 'David' }

if(person.name) {
  // Do stuff if property exists
}

if(1 == 1) {

}

Falsy values

false
null
undefined
0
''
person.undefinedProperty

Presenter Notes

Equality or == vs ===

== and != compare the value

1 == 1 // -> true
1 == '1' // -> true
1 == 2 // -> false

// Now things get weird
'' == false // -> true
[] == false // -> true
null == undefined // -> true

=== and !== compare value and type

1 === 1 // -> true
1 === '1' // -> false
1 === parseInt('1') // -> true
[] === false // -> false
null === undefined // -> false

ALWAYS USE ===

Presenter Notes

Scope in JavaScript

JavaScript only knows function scope and can access all variables from its parent scopes:

var x = 'outer';
function count() {
    for(var i = 0; i < 10; i++) {
        var x = 'testing';
        var inner = function() {
            var y = 42;
        }

        inner();
    }
}

count();

Presenter Notes

Global variables

Variables declared without var will automatically become global

function test() {
    var local = 42;
    global = 'global';
}

test();

You probably never want that.

If you do, add and access them through the window object (browsers) explicitly:

function test() {
    var local = 42;
    window.global = 'global';
}

test();

Presenter Notes

Closures

Introduce a new scope by passing variables to a wrapper function.

for(var i = 0; i < 10; i++) {
    var button = $('<button>Button #' + i + '</button>');
    var wrapper = function(counter) {
        button.click(function() {
            alert(counter);
        });
    }

    wrapper(i);
    $('body').append(button);
}

Presenter Notes

What is this?

In JavaScript this refers to the owner of the function you are calling, e.g. with

Objects

var person = {
    name: 'David',
    sayHi: function() {
        alert('Hello ' + this.name);
    }
}

person.sayHi();

jQuery

$('button').click(function() {
    this.html('Button clicked');
});

Presenter Notes

The Trinity of this

There are three rules for what this can be:

1) The object, when the function is called on an object

person.sayHi()

2) A function is called with the new operator

new Dog('Goofy');

3) The owner has been changed with call, apply or bind.

sayHi.call(owner, arg1, arg2);
sayHi.apply(owner, argsArray);

var boundSayHi = sayHi.bind(owner);

Otherwise this will be the global (window) object (or undefined in strict mode).

Presenter Notes

this and callbacks

Callbacks are used for asynchronous operations (the A in Ajax).

Always remember that in the callback you will loose the original this:

$('button').click(function() {
    // Store the old this reference (the clicked button)
    var self = this;

    $.getJSON('someFile.json', function(data) {
        // Set the button content
        self.html(data.text);
    });
});

Presenter Notes

Prototypes

Presenter Notes

Classes vs. Prototypes

Prototype vs. Class

Presenter Notes

JavaScript only knows objects

Inheritance by pointing an objects prototype to another object.

var Animal = function() {
    this.sound = 'blubb';
}

Animal.prototype.makeSound = function() {
    return this.sound + '!';
}

var Dog = function() {
    this.sound = 'Woof';
}

Dog.prototype = new Animal();

var Cat = function() {
    this.sound = 'Meow';
}

Cat.prototype = new Animal();

Presenter Notes

Overriding existing methods

If you want to overwrite an existing method but use the old result you need to call or apply the old function with the current this reference and arguments:

Dog.prototype.makeSound = function() {
    var oldSound = Animal.prototype.makeSound.apply(this, arguments);
    return this.sound + ' ' + oldSound;
}

var goofy = new Dog();
var garfield = new Cat();

alert(goofy.makeSound());
alert(garfield.makeSound());

Presenter Notes

The true ECMAScript 5 way

Uses only objects and inherits with Object.create(prototypeObject)

var Animal = {
    sound: 'blubb',
    makeSound: function() {
        return this.sound + '!';
    }
}

var Dog = Object.create(Animal);
var Cat = Object.create(Animal);

Dog.sound = 'woof';
Cat.sound = 'meow';

var goofy = Object.create(Dog);
var garfield = Object.create(Cat);

alert(goofy.makeSound());
alert(garfield.makeSound();

Presenter Notes

This year

We will try to make all meetups available online (but lure you to come out with swag, pizza and beverages).

From now on meetups will be split into two parts:

  1. The First 1 hour block will be on beginner topics (basic JavaScript, jQuery, CSS, HTML)
  2. The Second 1 hour block will be on a (related) advanced topic

BeerJS

Presenter Notes

Thursday, March 27th 2014

  1. jQuery 202

    • Un-spaghetti and modularize your code
    • Adanced selectors and DOM traversal
    • Making your code faster
    • Writing your own plugins
  2. Web components - the future of web development

    • Introduction to web components with Polymer
    • Data driven views
    • Build web components now with CanJS

Presenter Notes