List the methods of an object in JavaScript
Intermediate · 3 min read
When you meet a new object, whether it is a library, a built-in like Array, or a class someone else wrote, it helps to ask: "what can this thing do?" In other words, which of its properties are functions? Those are its methods.
In this tutorial you will write methodsOf(obj), which lists the methods of an object. You will see why Object.keys finds nothing on built-ins, why class methods don't show up on instances, and how to guard against a property that throws when you read it. You need to know objects, arrays and filter.
Methods are just properties
A method is a property whose value is a function:
const bus = { plate: 'X', go() {} };
console.log(typeof bus.go); // function
console.log(typeof bus.plate); // string
typeof tells you what kind of value you have. So the plan is: get every property name, then keep the ones whose value is a function.
Hidden properties and prototypes
Two ideas from earlier lessons matter here. First, properties can be non-enumerable, which means lists like Object.keys skip them. All built-in methods are non-enumerable. Second, objects can borrow properties from a prototype. Class methods live on the class's prototype, not on each object you make.
Here is the exercise. Try it yourself first if you like, or build it with us step by step.
11 List the methods of an object
fairList the function-valued properties of an object. The expected list for Array includes names that no longer exist, so check rather than trust.
Stuck? Three hints, smallest first
- 1.
Object.getOwnPropertyNamesreaches non-enumerable properties;Object.keysdoes not, and built-ins are non-enumerable. - 2. Filter on
typeof obj[key] === ‘function’. - 3. Reading some inherited properties of a function throws in strict mode, so guard the read.
Step 1: Object.keys sees nothing
console.log(Object.keys(Array)); // []
Array has plenty of methods, like Array.isArray, but they are all non-enumerable, so Object.keys returns an empty list. Object.getOwnPropertyNames includes non-enumerable names:
const names = Object.getOwnPropertyNames(Array);
console.log(names.includes('isArray'), names.includes('length')); // true true
length is there too, but it is a number, not a method. We need to filter.
Step 2: keep only the functions
const firstTry = (obj) => Object.getOwnPropertyNames(obj).filter((key) => typeof obj[key] === 'function');
console.log(firstTry(Array).includes('isArray')); // true
console.log(firstTry(Array).includes('length')); // false
That works for Array. Now try it on Function.prototype, the object every function borrows from:
try { firstTry(Function.prototype); } catch (e) { console.log(e.constructor.name); } // TypeError
It crashes. Function.prototype has properties named caller and arguments, and simply reading them throws a TypeError. One bad property breaks the whole list.
Step 3: guard each read
Wrap the read in try...catch, and treat a property that throws as "not a method":
function methodsOf(obj) {
return Object.getOwnPropertyNames(obj).filter((key) => {
try { return typeof obj[key] === 'function'; } catch { return false; }
});
}
console.log(methodsOf(Function.prototype).includes('bind')); // true
console.log(methodsOf({ go() {}, plate: 'X' })); // [ 'go' ]
console.log(methodsOf({})); // []
catch with no brackets is allowed when you don't need the error itself.
Step 4: don't trust old lists
You may find older articles that list observe and unobserve among the methods of Array. Those were part of an experiment that was withdrawn and never became standard JavaScript. Check rather than trust:
const own = Object.getOwnPropertyNames(Array);
console.log(own.includes('observe'), own.includes('unobserve')); // false false
console.log(methodsOf(Array).includes('from'), methodsOf(Array).includes('of')); // true true
The exact list can grow as new methods are added to the language, so a check like includes is safer than comparing to a fixed list.
Step 5: class methods live on the prototype
class Bus {
constructor(plate) { this.plate = plate; }
board() {}
depart() {}
}
console.log(methodsOf(new Bus('LAG-441-XA'))); // []
console.log(methodsOf(Bus.prototype)); // [ 'constructor', 'board', 'depart' ]
The bus object itself only owns plate. board and depart sit on Bus.prototype, which every bus borrows from. constructor is there too: it points back to the class.
Step 6: walk up the chain
To see everything a bus can do, look at the object, then its prototype, then that prototype's prototype, and so on. Object.getPrototypeOf gives the next one up. Stop before Object.prototype, or every answer ends with toString, valueOf and the rest:
function allMethodsOf(obj) {
const found = new Set();
for (let o = obj; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {
for (const key of methodsOf(o)) found.add(key);
}
return [...found];
}
console.log(allMethodsOf(new Bus('LAG-441-XA'))); // [ 'constructor', 'board', 'depart' ]
A Set ignores repeats, so a name found on two levels is listed once. [...found] turns it back into an array.
The full solution
The panel lists the own property names and methods of Array, checks the withdrawn names one by one, then shows the Bus instance, its prototype and the chain walk. Press Run to see them.
function methodsOf(obj) {
return Object.getOwnPropertyNames(obj).filter((key) => {
// Some properties are accessors that throw when read (fn.caller in strict
// mode). A plain typeof check would blow up on them.
try { return typeof obj[key] === 'function'; } catch { return false; }
});
}
// Own methods only misses inherited ones, which is usually what you want to see.
function allMethodsOf(obj) {
const found = new Set();
for (let o = obj; o && o !== Object.prototype; o = Object.getPrototypeOf(o)) {
for (const key of methodsOf(o)) found.add(key);
}
return [...found];
}
class Bus {
constructor(plate) { this.plate = plate; }
board() {}
depart() {}
}
console.log('own property names of Array:', Object.getOwnPropertyNames(Array));
console.log('methods of Array :', methodsOf(Array));
console.log("--- that older list is from an older engine ---");
for (const name of ['isArray', 'from', 'of', 'observe', 'unobserve', 'arguments', 'caller']) {
console.log(String(name).padEnd(12), 'own property of Array?', Object.getOwnPropertyNames(Array).includes(name));
}
console.log('--- a class puts its methods on the prototype ---');
console.log('own methods of an instance :', methodsOf(new Bus('LAG-441-XA')));
console.log('methods on the prototype :', methodsOf(Bus.prototype));
console.log('walking the chain :', allMethodsOf(new Bus('LAG-441-XA')));
Output
15 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('isArray is a method of Array', methodsOf(Array).includes('isArray'), true);
test('so is from', methodsOf(Array).includes('from'), true);
test('and of', methodsOf(Array).includes('of'), true);
test('observe no longer exists', Object.getOwnPropertyNames(Array).includes('observe'), false);
test('nor does unobserve', Object.getOwnPropertyNames(Array).includes('unobserve'), false);
test('arguments is not an own property of Array', Object.getOwnPropertyNames(Array).includes('arguments'), false);
test('nor is caller', Object.getOwnPropertyNames(Array).includes('caller'), false);
test('length and name are properties but not methods', methodsOf(Array).includes('length') || methodsOf(Array).includes('name'), false);
test('prototype is not a function either', methodsOf(Array).includes('prototype'), false);
test('Object.keys finds nothing, because built-ins are non-enumerable', Object.keys(Array).length, 0);
test('an instance has no own methods', methodsOf(new Bus('X')), []);
test('they live on the prototype', methodsOf(Bus.prototype).sort(), ['board', 'constructor', 'depart']);
test('walking the chain finds them from the instance', allMethodsOf(new Bus('X')).includes('board'), true);
test('a plain object with a function property', methodsOf({ go() {}, plate: 'X' }), ['go']);
test('an empty object has none', methodsOf({}), []);
Older references list ["length", "name", "arguments", "caller", "prototype", "isArray", "observe", "unobserve"]. Today's answer is ["length", "name", "prototype", "isArray", "from", "of", ...]. Array.observe and Object.observe were an experiment that was withdrawn and never standardised; arguments and caller are no longer own properties of functions. The assertions check for their absence, so this exercise documents the change rather than repeating a stale list.
Two mechanics matter. Object.keys(Array) returns nothing at all, because every built-in method is non-enumerable — that is why getOwnPropertyNames is required here. And class methods are not own properties of instances; they sit on the prototype, which is why methodsOf(new Bus(...)) is empty and the chain has to be walked.
Common mistakes
- Using
Object.keyson built-ins. Built-in methods are non-enumerable, so you get an empty list. - Reading every property without a guard. Some, like
calleronFunction.prototype, throw when read. - Looking for class methods on the instance. They are on the prototype. Walk the chain or look at
Class.prototype.
Try it yourself
- List the methods of
MathwithmethodsOf. IsPIincluded? Why not? - Add a method
stop() {}toBusand check it appears inallMethodsOf. - Make
class Minibus extends Buswith its ownhonk() {}, and list all methods of a minibus.