Skip to content

How to list all methods of an object in JavaScript

New Course Coming Soon:

Get Really Good at Git

Find out how to get an array with a JavaScript object methods

We can use the Object.getOwnPropertyNames() function to get all the property names linked to an object.

Then we can filter the resulting array, to only include that property name if it’s a function.

We determine if it’s a function by using typeof on it.

For example here is how we might create a utility function to do what we need:

getMethods = (obj) => Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function')

This lists only the methods defined on that specific object, not any method defined in its prototype chain.

To do that we must take a slightly different route. We must first iterate the prototype chain and we list all the properties in an array. Then we check if each single property is a function.

An easy way to make sure we don’t duplicate methods as we navigate the prototype chain (like constructor which is always present), we use a Set data structure that makes sure values are unique:

const getMethods = (obj) => {
  let properties = new Set()
  let currentObj = obj
  do {
    Object.getOwnPropertyNames(currentObj).map(item => properties.add(item))
  } while ((currentObj = Object.getPrototypeOf(currentObj)))
  return [...properties.keys()].filter(item => typeof obj[item] === 'function')
}

Example usage:

getMethods("")
getMethods(new String('test'))
getMethods({})
getMethods(Date.prototype)
Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching Summer 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: