How to define a method in JavaScript?


A method in JavaScript is the action performed on objects. A JavaScript method has a function definition, which is stored as a property value. 

Example

Let’s see an example to define a method in JavaScript

Live Demo

<!DOCTYPE html>
<html>
   <body>
      <h3 id="myDept"></h3>
         <script>
            var department = {
               deptName: "Marketing",
               deptID : 101,
               deptZone : "North",
               details : function() {
                  return "Department Details<br>" + "Name: " + this.deptName + " <br>Zone: " + this.deptZone + "<br>ID: " + this.deptID;
               }
            };
         document.getElementById("myDept").innerHTML = department.details();
      </script>
   </body>
</html>

Updated on: 07-Jan-2020

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements