Difference between functions and methods in JavaScript

Ekaterine Mitagvaria - Jan 26 '23 - - Dev Community

Is there a difference between a function and a method?
When you start learning functions and methods in JavaScript you might use these words interchangeably because both seem so similar.
However, that is not the case as functions and methods are different things.

Definition

Definition

A function is a block of code 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

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.

Function

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. However, you can create them yourself as well.

Method

Existence

Existence

A function can exist on its own and does not have to be attached to anything. 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 be someone's property with a function value. It cannot exist on its own.

Calling

Calling

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

call a function

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

call a method

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.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player