Syntax error What is the difference between functions and methods in JavaScript?

What is the difference between functions and methods in JavaScript?



Functions and methods are the same in JavaScript, but a method is a function, which is a property of an object.

The following is an example of a function in JavaScript −

function functionname(param1, param2){
   // code
}

Example

The method is a function associated with an object. The following is an example of a method in JavaScript −

 Live Demo

<html>
   <head>
      <script>
         var employee = {
            empname: "David",
            department : "Finance",
            id : 002,
            details : function() {
               return this.empname + " with Department " + this.department;
            }
         };

         document.write(employee.details());
      </script>
   </head>
</html>

Output

Updated on: 2020-06-23T05:53:17+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements