Difference between functions and methods in JavaScript

Difference between functions and methods in JavaScript

When you start learning functions and methods in JavaScript you might use these words as if it’s the same because they might sound and look similar sometimes however functions and methods are different things.

I will try to explain in a very simple way the difference between functions and methods in JavaScript.

Definition

A function is a block of code that is written to perform specific tasks.

A method is a property of an object and contains a function definition. In other words, a method is also a function but stored as an object property.

Syntax

A function is defined by using a keyword function followed by a name we come up with. The body is enclosed in curly braces.

A method is located inside objects and we access it by accessing the object first and then the method. There are types of methods that already exist in JavaScript, for example, strings or arrays already have built-in methods. Though you can create them yourself as well.

Existence

A function can exist on its own and does not have to be attached to anyone. However, at the same time, it actually is attached to something and that is a global object. In any case, it’s still considered a function.

A method needs to be attached to objects and needs to be someone’s property with a function value. It cannot exist on its own.

Calling

To call a function you can use various ways and one of them can be calling the function with its name or it can even call itself(self-invoking function).

To call a method you need to use the object name first and separate it from a method name with a dot.

To summarize, in JavaScript, a function is a block of code that can be defined and then invoked, while a method is a function that is associated with an object. The key difference between the two is that a method has access to the properties and methods of the object it is associated with, while a function does not. Understanding the difference between functions and methods is important because it allows developers to use the appropriate tool for the job, and can help improve code organization and readability. Additionally, understanding the difference can also help prevent common programming errors, such as attempting to use a method as a function or vice versa.