So what’s the different between the two?
- Methods have a “receiver” while functions do not.
- Functions and methods are the same in JavaScript, but a method is a function, which is a property of an object.
- Syntax for calling/ definition/declaration of functions and methods are different.
- A function can be called directly by its name but methods are called by its object name and its method name using dot notation or square bracket notation.
- Function passes the data and methods operates the data passed in the class.
- A function lives on its own but method is a function associated with an object property.
- Data passed to a function is explicit but method implicitly passes the object on which it was called.
Lets see detailed difference between them:-
A function in JavaScript is similar to a procedure —>a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output
Few Important things of functions:-
- The function is executed when something calls/invokes it.
- The name may contain letters, digits, dollar signs, underscore.
- Parameters are listed inside round parenthesis after the name of the function.
- Arguments are values a function receives when it is invoked.
- When the control reaches the return statement, js will stop executing and the value is returned to the caller.
There are three steps of Functions as well as Methods to use in the program.
- Declaration
- Definition.
- Call
In JavaScript function declaration and definition are mostly done together.
A JavaScript method is a property of an object that contains a function definition. Methods are functions stored as object properties.
Few Important things of Methods:-
- In JavaScript, however, a method is a function that belongs to an object.
- JavaScript methods are the actions that can be performed on objects.
- A JavaScript method is a property containing a function definition.
- Accessing the object method is done with the following syntax: objectName.methodName()
Syntax of Function
var func = function(a, b) {
var sum = a + b;
return sum;
}
console.log(sum(1, 2));
Syntax of Methods
object = {
methodName: function() {
// Content
}
};
object.methodName()
Few important links for learning:-
- Let’s see an example for User form validation in JavaScript. click here.
- Let’s understand JavaScript. what and how? click here.
- Want to know what is function and how to use them in JavaScript? Just click here.
- Want to know what are variables and how to use them in JavaScript? Just click here.
[…] Want to know the difference between Function and Method in JavaScript? Just click here. […]
[…] Want to know the difference between Function and Method in JavaScript? Just click here. […]