Functions Versus Methods

When I first started programming, I remember encountering functions and methods. I was familiar with functions from high school algebra, but I had no idea what a method was. They looked similar to functions, and online comments indicated they were essentially interchangeable.

When you are getting started, you can think of functions and methods as more-or-less the same thing, but they have one important difference. With functions all arguments must be passed in explicitly when they are called. Arguments for methods are also passed in, but methods have access to an additional implicit argument (also called a context object). In JavaScript this argument is this. In Ruby this argument is self.

let sweetee = {
	name: 'Sweetee'
};

let speak = function (pet) {
	console.log(pet.name);
};

speak(sweetee);
Here we see speak expressed as a function. Notice that we are explicitly passing in an object on which to find a name.
let sally = {
	name: 'Sally',
	speak: function () {
		console.log(this.name);
	}
};

sally.speak();
In this example, speak is treated as a method. Notice that we are relying on the JavaScript runtime to assign the context object (this) implicitly.