Saturday, October 25, 2025
HomeLanguagesJavascriptHow to get all the methods of an object using JavaScript ?

How to get all the methods of an object using JavaScript ?

In this article, we will learn how to get all the methods of an object using JavaScript. In JavaScript, we can get all the methods of an object by iterating over each object and checking if its property value is a function. An HTML document contains some methods and the task is to get all methods of the object.

There are two methods to solve this problem which are discussed below:

Approach 1: Use typeof operator and filter() Methods

  • Create a function that takes an object as input.
  • Use typeof operator, which checks if the type of object is a function or not.
  • If the type of object is a function then it returns the object.

Example: This example implements the above approach. 

Javascript




function Obj() {
    this.m1 = function M1() {
        return "From M1";
    }
    this.m2 = function M2() {
        return "From M2";
    }
}
 
function getAllMethods(obj = this) {
    return Object.keys(obj)
        .filter((key) => typeof obj[key] === 'function')
        .map((key) => obj[key]);
}
 
function gfg_Run() {
   console.log(getAllMethods(new Obj()));
}
gfg_Run();


Output

[ [Function: M1], [Function: M2] ]

Approach 2: Use typeof operator and for-in loop

  • Create a function that takes an object as input.
  • Use typeof operator, which checks if the type of object is a function or not. This example also checks if any error occurred or not and if occurred then handle it properly.
  • If the type of Object is a function then return it.

Example 2: This example implements the above approach. 

Javascript




function Obj() {
    this.m1 = function M1() {
        return "From M1";
    }
    this.m2 = function M2() {
        return "From M2";
    }
}
 
function getAllMethods(obj) {
    let result = [];
    for (let id in obj) {
        try {
            if (typeof (obj[id]) == "function") {
                result.push(id + ": " + obj[id].toString());
            }
        } catch (err) {
            result.push(id + ": Not accessible");
        }
    }
    return result;
}
 
function gfg_Run() {
   console.log(getAllMethods(new Obj()).join("\n"));
}
gfg_Run();


Output

m1: function M1() {
        return "From M1";
    }
m2: function M2() {
        return "From M2";
    }
RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS