What is the difference between functions and methods in JavaScript?

JavascriptWeb DevelopmentFront End Technology

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

raja
Published on 23-Feb-2018 12:03:22
Advertisements