
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the difference between a method and a function?
In this article, we will learn about the difference between a method and a function in Javascript. Method and a function are the same, with different terms. A method is a procedure or function in object-oriented programming.
What is a Function?
A function is a group of reusable code that can be called anywhere in your program. This removes the necessity to repeat the same code over and over, assisting developers in writing modular code.
JavaScript functions can be defined in a number of ways, such as function expressions, arrow functions, or the function keyword.
The following is the syntax of a JavaScript function ?
<script type="text/javascript"> <!-- function functionname(parameter-list) { statements } //--> </script>
Example
Below is an example of a function in JavaScript ?
<script type="text/javascript"> <!-- function sayHello() { alert("Hello there"); } //--> </script>
What is a Method?
A method is a function that belongs to an object. It is an object attribute that is employed as a function. A function employed as a part of an object is referred to as a method. Methods are able to operate on the object's properties and access or modify those properties.
Methods are commonly used in object-oriented programming in JavaScript to define behavior related to objects.
Example
Below is an example of a method in JavaScript ?
let person = { name: 'Alice', greet: function() { console.log('Hello, ' + this.name + '!'); } }; person.greet();
Output
Output: Hello, Alice!
Comparison Table
The following table shows the differences between a function and a method ?
Feature | Function | Method |
Definition | A standalone block of code that performs a task. | A function that is associated with an object. |
Invocation | Called by its name: functionName(). | Called using an object: objectName.methodName(). |
Association | Not associated with any object unless explicitly assigned. | Always belongs to an object as one of its properties. |
Usage | Used for general-purpose logic, reusable operations, or utility functions. | Defines behavior related to a specific object. |