JavaScript - Function Fundamentals

by johnpapa

JavaScript

// *** Normal function ***
// Function that acts like a method.
// Intention is that you just call it when needed.
// Notice its not set to a var. I dont like doing this because it // implicitly defines a function on the fly.
function sayHi(person) {
    console.log('hi ' + person.firstName);
};

// *** Anonymous function assigned to a variable ***
// Another function, this time set to a variable.
// This one is explicitly defined.
var sayHiToAll = function(people) {
    for (var i = 0; i < people.length; i++) {
        sayHi(people[i]);
    }
};



// *** Anonymous function assigned to a variable ***
// Function that will be 'newed' up so you can 
// instantiate one or more of them
var Person = function(first, last) {
    var self = this;
    this.firstName = first;
    this.lastName = last;
};

var people = [];

// Newing up the Person objects and adding them to the array.
// Functions are objects. 
// So when you new one up, you get an object instance with state.
people.push(new Person('Julie', 'Lerman'));
people.push(new Person('John', 'Papa'));
people.push(new Person('Scott', 'Guthrie'));
people.push(new Person('Rowan', 'Miller'));
people.push(new Person('Bill', 'Gates'));

// Call a method/function
sayHiToAll(people);