A function in JavaScript is a statement that performs a task or calculates a value, takes in an input, and returns an output as a result of the relationship between the input. A method is a property of an object that contains a function definition. Methods are functions stored as object properties.
Let us use an object called rectangle
.
class Rectangle{}
We want to use the code to find the area of a rectangle to establish the difference between a function and a method.
//We create an object called Rectangleclass Rectangle {//We initialize the constructorconstructor(width, height) {this.height = height;this.width = width;}//A function local to the Rectangle classgetArea() {return this.width * this.height;}}//Let us initalize a new Rectangle with a width of 10 and 5AreaOfRect = new Rectangle(10, 5);console.log(AreaOfRect.getArea());//console.log(getArea())
Let us go into functions before we do our comparison.
const AreaRect = (width, height) => {return console.log(width * height);};AreaRect(10,5); //50
A method, like a function, is a collection of instructions that perform a task, but a method is associated with an object and a function is not.
So, if we want to call a method from our code, we will use AreaOfRect.getArea()
. If we use getArea()
here, we will get an error because getArea()
is local to the AreaOfRect
object. We need to access the getArea()
function as an object property from the AreaOfRect
object.
We can assume our AreaRect()
function is global, meaning it can be called without being used as an object property. I can simply call AreaRect(5,10)
and it gives me an output of 50.