Week 2 - JavaScript functions, events & callbacks
More on JavaScript - variables, loops, conditions, functions, events and callbacks - the things that maker JS special.
Tools
Google Chrome JavaScript console
Google Chrome Javascript console is a great way test JavaScript right within any webpage. You can access from the menubar, View -> Developer -> JavaScript Console. Or by pressing the Option+Command+J keys.
NodeJS in Terminal/Shell
With NodeJS installed, you can run JavaScript files within the Terminal application (Terminal installed on all OSX). Within Terminal, navigate to the code directory that contains your .js file. To navigate to your code directory, * Open Terminal. * Open Finder window find the .js directory. * In Terminal, type 'cd ' * Drag the folder icon from the Finder window to the Terminal. Something like this... cd /user/someone/Desktop/file.js * Press 'return' key to run file.
Variables
Basics
var myStr = "Hello world"; // this is a string
var answer = 42; // a number
var isNYU = true; // boolean
Arrays
var favPies = ['blueberry','cherry','apple','grape']; // an array. yes, grape pie is a thing.
favPies.push('pumpkin');
Objects
// an object
var contactInfo = {
name : 'Tony Pony',
address : '123 Street',
zip : 10003,
favPies : ['coconut custard','lemon']
};
// array of objects
var grades = [
{name:'Dan', pass: true},
{name:'Robbie', pass: false},
{name:'Jenny', pass: true},
{name:'Shelly', pass: true}
];
Conditions
if(condition)
if (1 == 1) {
console.log("they match!");
}
var isSnowing = true;
var isSummer = true;
if (isSnowing == true) { console.log("Get the sleds"); }
// multiple conditions using the && (and) operator
if (isSnowing && isSummer) {
console.log("Why is it snowing?");
}
// negate condition with !
if ( !isSummer ) {
console.log("I miss Summer");
}
// the OR operator
var hasInternet = true;
var hasHeat = false;
if ( hasHeat || hasInternet ) {
console.log("Have at least 1 essential item.");
}
if(condition) / else if(condition) / else
var age = 25;
var isCitizen = true;
if (age > 18 && isCitizen == true) {
console.log("You can vote.");
} else if ( isCitizen == false) {
console.log("You must be a US citizen to vote in the US elections.")
} else {
console.log("You must be at least 18 to vote in the US.");
}
Looping
FOR loop
var favPies = ['blueberry','cherry','apple','grape'];
for (i=0; i<favPies.length; i++) {
console.log("I love " + favPies[i] + " pie!");
}
FOR IN loop
var favPies = ['blueberry','cherry','apple','grape'];
for (i in favPies) {
console.log("I love " + favPies[i] + " pie!");
}
Functions
JavaScript functions are variables too! Declare them with 'var'.
var sayHello = function() {
console.log("Hello");
};
sayHello();
Function Arguments
Passing data into functions
var saySomething = function(words) {
console.log(words);
};
saySomething('JavaScript functions are friendly.');
Multiple arguments
var repeatYourself = function(words,number) {
for (counter=0; counter<number; counter++) {
console.log(counter + ". " + words);
}
};
repeatYourself('yo',10); //say 'yo' ten times
Pass Object into Function
var printObject = function(myObj) {
console.log("Let's look inside the object...");
for (p in myObj) {
console.log(p + " = " + myObj[p]);
}
};
var movie = {
title : 'The Explorers',
year: 1985,
director : 'Joe Dante',
cast : ['Ethan Hawke','River Phoenix','Bobby Fite'],
description: "This adventurous space tale stars Ethan Hawke and young star River Phoenix as misfit best friends whose dreams of space travel become a reality when they create an interplanetary spacecraft in their homemade laboratory."
};
printObject(movie);
Return data from function
var square = function(num) {
return num * num;
};
var cube = function(num){
return num * square(num);
}
fivesq = square(5);
fivecube = cube(5);
console.log( fivesq );
console.log( fivecube );
Returning an object from function
var createMessage = function(recipient, message) {
mailObj = {
to : recipient,
message : message,
date : new Date(),
hasSent : false
};
return mailObj;
};
myMessage = createMessage('Red','Thanks for ITP.');
console.log(myMessage);
Callbacks
JavaScripts magic (and beginner's stumbling blocks) comes from callbacks.
- Callbacks allow the execution of a function to include 'next' steps when the requested function finishes.
- Callbacks are functions passed into a function.
Helpful links
Passing in functions to functions
var say = function(word) {
console.log(word);
}
var computerTalk = function(words, theFunction) {
theFunction(words);
}
computerTalk("Hello", say);
Anonymous functions
var bigCounting = function(number, myCallback) {
for(i=0; i<number; i++){
// do nothing - just wasting time
}
myCallback('All finished');
}
bigCounting(1000000, function(response){
console.log('Finished counting.');
console.log('response = ' + response);
});
Functions as Classes
If you're into Object Oriented Program JavaScript functions can be used as Classes and can create Objects of similar properties and methods/functions.
More info
*JS Functions and Objects - StackOverflow
var ITPClass = function(name, instructor, day) {
this.name = name;
this.instructor = instructor;
this.day = day;
this.describe = function() {
console.log(this.name + " is taught by " + this.instructor + " on " + this.day);
}
}
var DWD = new ITPClass('Dynamic Web Development','John Schimmel','Friday');
DWD.describe();
// add a new method/function to ITPClass
ITPClass.prototype.hollar = function() {
alert(this.name);
}
var POPUPBooks = new ITPClass('Pop Up Books','Marianne Petit','Monday');
POPUPBooks.hollar();
Practice, practice, practice. Start with data structures, then move to objects and functions. Lots of resources online. Ask if you have any questions.
Assignment
Prepare for Heroku!
- Create a Heroku account, https://api.heroku.com/signup. Be sure to confirm your account and put a credit card number on your account. You will not be charged until you turn on more than 2 instances, we will only be using a single instance.
- Install the Heroku Toolbelt, this will let us push code to Heroku. https://toolbelt.heroku.com/.