JavaScript for Designers

An Intro to JS Terms and Concepts

RachelNabors.com @RachelNabors

A manga-inspired self-portrait of Rachel, clutching a laptop and looking adorable.
with Rachel the Great (aka Rachel Nabors)

I am Rachel the Great Nabors

A cartoonist turned web designer turned front end developer

Rachel the Great and her talking cat Tuna, waving.
(You can still read the comic adventures of Rachel and Tuna at RacheltheGreat.com)

I am not a hardcore JavaScript developer.

I pout while a man holding a copy of JavaScript the Good Parts tells me I wouldn't understand, it's not for me.

Most JS study materials are written by programmers for programmers—not designers.

You are…

People suffering from broken code, inability to understand developers, and imposter syndrome.

Why learn JavaScript?

Can't you just use a library or a plugin or ask someone else to do it?

UNICORNS DO ALL THE THINGS

We will cover…

A handful of all the things:

Hello, JavaScript

ECMAScript is JavaScript

Like CSS and HTML, JavaScript has versions and a standard.

ECMA” stands for “European Computer Manufacturers Association”

Most of us code for version 3, but 5 is well supported, and 6 is on the way.

jQuery is written in JavaScript

If you're just getting into this space, you might be confused.

jQuery is a JavaScript Library

Libraries are collections of code that lets you do big things without having to write a lot of code yourself.

Zepto.js ember.js angular.js impact.js

Vanilla JS is JavaScript

Vanilla JS is just JavaScript.

JavaScript is pretty powerful now. You don't necessarily need libraries like jQuery.

$('p'); // jQuery gets p

document.querySelectorAll('p'); // Regular ol' JS gets p

JavaScript isn't Java

Raise your hand if you knew that already.

Objects

Everything is an Object

Understand objects and you will understand JavaScript. Cody Lindley, JavaScript Enlightenment

What does an Object look like?

Objects are just collections of things, things called properties.

unicorn
property: property value:
name Twilight Sparkle
color purple
wings true
getName function() {
  return "Hi, I'm " + unicorn.name;
}

Making Objects

You can make an object using an Object Literal:

var unicorn = {
  name: "Twilight Sparkle",
  color: "purple",
  wings: true,
  getName: function() {return "Hi, I'm " + unicorn.name;}
};

Object literals are the preferred way to make objects.

Declaring Variables

You can store objects as variables.

var unicorn = {};
unicorn.name = "Rarity";
unicorn.color = "white";
unicorn.wings = false;
unicorn.getName = function() {return "Hi, I'm " + unicorn.name;};

Complex objects

There are many different kinds of objects. Let's start with these.

They're complex because they can contain lots of complicated data.

Primitive Values

Primitive Values are the simplest forms of information an object can represent.

Comparing Complex Objects

Complex objects don't compare by their values

var castles = ["summer", "winter"];
var pegasi = ["Rainbow Dash", "Fluttershy"];

castles === pegasi; // compares two Objects(), not their numeric values

Comparing Primitives

Primitives are not objects. They're values.

var castles = 2;
var pegasi = 2;

castles === pegasi; // compares two numeric values

Learn more about why we're using === on your own.

The Global Object: God of objects

All of these objects exist inside one big catch-all object: the Global Object.

In the browser, the window is that Global Object.

It is also called the Head Object or Host Object.

It is inferred: window.alert("OMG!") is the same as alert("OMG!")

Objects at Work

Using Objects with jQuery

We pass objects in jQuery all the time!

$.ajax({ // an ajax call
  url : 'info.json',
  success : function (data) {
    console.log("Success: " + data);
  }
});

$("mark").css({ // modifying css
  "color": "#a52469",
  "font-weight": "bold",
  "font-size": "2em"
});

Don't Repeat Yourself!

But say we needed to use the same object over and over…

$("mark").css({
  "color": "#a52469",
  "font-weight": "bold",
  "font-size": "2em"
});

$("input").click(function(){
  $(this).css({
    "color": "#a52469",
    "font-weight": "bold",
    "font-size": "2em"
  });
});

Work on it live in CodePen!

There's a variable for that

Just put that object in a variable and pass it around!

var highlight = {
  "color": "#a52469",
  "font-weight": "bold",
  "font-size": "2em"
};

$("mark").css(highlight);

$("button").click(function(){
  $(this).css(highlight);
});

Functions

Functions are objects!

Functions are first-class objects, meaning they can be:

Methods

When a function is a property of an object, it is called a method (of that object).

unicorn
property: property value:
name Twilight Sparkle
color purple
wings true
getName function() {
  return "Hi, I'm " + unicorn.name;
}
var unicorn = {
  name: "Twilight Sparkle",
  color: "purple",
  wings: true,
  getName: function() {return "Hi, I'm " + unicorn.name;}
};

Making a function

// function statement
function addStatement(x, y) {
  return x + y; 
}

// function expression
var addExpression = function(x, y) {
    return x + y;
};

Functions do stuff

Functions can be used to construct objects, return a value, or just run code.

Think of them as the verbs of JavaScript.

document.querySelectorAll("p");

Invoking a Function

To run a function, it needs parentheses.

$("#thief").hide();

Anything you put inside those parentheses are arguments the function can use.

function addition(x, y) {
  return x + y; 
}

Returning from a function

return lets us return a value or object from a function.

function redHen() {
    return {
        laidEggs: "5 eggs",
        poops: "5 times a day"
    }
    console.log("Plot against the humans."); // doesn't happen, after return
}

var henrietta = redHen(); // create an object via a function

It also stops the execution of the rest of the function.

Anonymous Functions

A function wearing an adorable Guy Fawkes mask.

Anonymous functions are like disposable functions, use as needed.

$("#rebel").click(function() { //anonymous function 
  console.log("The new world order has begun.");
});

Callbacks

A callback is when you pass a function to another function to be executed at a later time.

$("#goodbye").click(function(){ //execute after click event
  alert("Holla back, y'all!");
});
setTimeout(function(){ //execute after 3 seconds
  alert("Ready for lift off.");
},3000);

Functions that take a function as an argument or return a function are higher-order functions.

Making Objects with Functions

Constructor Functions

Useful if you need to make numerous objects of the same kind of thing.

// making a constructor function with a function expression!
var Unicorn = function(name, color, wings) { 
  this.name = name;
  this.color = color;
  this.wings = wings;
  this.getName = function() {return "Hi, I'm " + this.name;};
};

var twilightSparkle = new Unicorn('Twilight Sparkle', 'purple', true);

twilightSparkle.constructor

Scoping Variables

Variables declared in functions are accessible only from the function.

var cat = "An adorable pet that purrs cutely."; //global cat

animalpedia = function() {
  var cat = "A menace to birds."; //local cat
  console.log(cat);
}

GOTCHA! If you don't use var inside a function, the variable belongs to the global scope!

this

When you make a function, a this is born.

this is like a variable that refers to the context in which the method was called.

var ourObject = {
  func: function() {
    console.log(this); // refers to the context
  }  
}

ourObject.func(); // in ourObject context
    

this and the Global Object

By default, this refers to the Global Object (because it's the big catch-all).

console.log(this);

This can lead to some misunderstandings!

var newFunc = ourObject.func; 
newFunc(); // in the Global Object context!

Functions at Work

The jQuery object, AKA $

By default, jQuery uses “$” as a shortcut for “jQuery”

So $("#id").hide(); is the same as jQuery("#id").hide();

jQuery is just a big function with many methods!

Using Functions with jQuery

We use functions with jQuery all the time.

$("#button1").click(function(){
  var buttonText = $("#button1").val();
  alert(buttonText);
});

$("#button2").hover(function(){
  var buttonText = $("#button2").val();
  alert(buttonText);
});

Work on it live in CodePen!

Don't repeat yourself!

Using this, it's easy to extract a reusable function.

var logButton = function(){
  var buttonText = $(this).val();
  alert(buttonText);
}

$("#button1").click(logButton);

$("#button2").hover(logButton);

The DOM API

What's an API?

An Application programming interface (API) is a set of rules different programs can use to talk to each other.

There are many APIs available to you.

Some, like the Web Audio API and Canvas API, are browser APIs.

Others, like Twitter's API, are provided so developers can interact with a company's data.

The DOM and jQuery

Every time you use JavaScript to manipulate the contents of a page, you're using the DOM, or Document Object Model API.

Every element in the HTML tree has a corresponding object available to JS called a node

jQuery provides normalized methods for getting at and manipulating the DOM.

The Global Object and document

In the browser, our Global Object window always has a document node: the HTML document.

Remember document from earlier?

$('p'); // jQuery gets p

document.querySelectorAll('p'); // Regular ol' JS gets p

Events and Listeners

Events and their Listeners

Events can be triggered by users, the browser, or JavaScript itself.

Event Listeners are functions that execute in response to an event.

Human and Browser Events

On the human end of that equation, see Mouse event handlers.

Look familiar?

$(document).ready(function () { 
  // Do stuff in here.
});

.ready() is a jQuery method whose callback runs when the DOM has been rendered.

Event Propagation

Events will “bubble” up through the DOM, triggering listeners on the way.

Stopping Propagation

You can stop propagation using one of jQuery's handy event methods.

$("a").click(function(event){
  // code for lightbox ...

  event.preventDefault();
});

Page Rendering and Event Listeners

Events should be attached after the DOM is rendered.

$(document).ready(function () { // when DOM is rendered...
  var clickOnLi = function() {
    alert("Clicking on list items!");
  }

  $("li").click(clickOnLi); // attach click handler
});

Events and Post-Rendering DOM manipulation

If you add an element to the DOM after page render, it won't get it's listener attached!

var addLi = function() {
  $("ul").append("
  • New element!
  • "); }

    Work on it live in CodePen!

    Listening higher up the DOM with jQuery

    The solution is to listen from higher up with jQuery's on.

    $("ul").on("click", "li", clickOnLi); //listens for clicks on uls only
    

    JavaScript isn't Scary

    Your new Best Friends

    JavaScript boils down to events, objects, and functions.

    Objects, Functions, and Event Listeners being best buddies.

    Learn moar!

    Links

    Books

    Thank you!

    Bookmark these slides: rachelnabors.com/javascript-for-designers

    Keep in Touch

    Special Thanks

    My thanks to @ScottGonzalez, @rmurphey, @ajpiano for technically reviewing my slides.

    Super Secret Bonus Round!!

    Getters and Setters

    In jQuery, some methods do double duty: they both set values and return values.

    Compare how you would do this in Vanilla JS with jQuery's methods.

    Getting

    //return the contents of a paragraph
    document.querySelector('h1').innerHTML; // Vanilla JS getting a property
    $("h1").html(); // jQuery method returning a property
    

    Setting

    // set or overwrite the contents of a paragraph
    document.querySelector('h1').innerHTML = "New text!"; // Vanilla JS setting a property
    $("h1").html("New text!"); // jQuery method setting a property
    

    Dive deep on getters and setters!

    Closures

    When variables are declared within a function, only the function and any functions it contains can access them.

    Closures happen when you nest a function inside a function…

    …and then use the variables of the containing function!

    A Closure in Action

    function princess() {
      var dragons = ["Great Blue", "Glitterfang", "Fafnir"]; // there are 3 dragons to slay
    
      return {
        slayDragon: function() {
          return dragons.pop(); //pop gets and removes the last array item
        }
      };
    }
    
    var littleGirl = princess(); //littleGirl is now secretly a princess
    
    // Now she can slay dragons no one can see.
    littleGirl.slayDragon(); 
    littleGirl.slayDragon(); 
    littleGirl.slayDragon(); 
    

    Inspired by my favorite explanation of closures ever.

    Deep dive on closures at javascriptissexy.com

    Hoisting

    You can use a function statement in a script before you define it, like so:

    var crow = function() {
        caw(); // caw() hasn't been defined yet, but you can still invoke it.
        function caw() {console.log('Caw caw caw!');}
    }(); // invoke, remember the parentheses?
    

    More reading on hoisting.

    Recursion

    Recursion is when a function calls itself. See this example from Cody Lindley:

    var countDownFrom = function countDownFrom(num) {
      console.log(num);
      num--;//reduce num by 1
      if (num < 0){return false;} // if num < 0 return function with no recursion
      countDownFrom(num);
    };
    countDownFrom(5); // kick off the function, which logs separately 5,4,3,2,1,0
    

    /

    #