JavaScript: Get an array of function property names from own enumerable properties of an object
JavaScript fundamental (ES6 Syntax): Exercise-48 with Solution
Write a JavaScript program to get an array of function property names from the own (and optionally inherited) enumerable properties of an object.
- Use Object.keys(obj) to iterate over the object's own properties.
- If inherited is true, use Object.getPrototypeOf(obj) to also get the object's inherited properties.
- Use Array.prototype.filter() to keep only those properties that are functions.
- Omit the second argument, inherited, to not include inherited properties by default.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const functions = (obj, inherited = false) =>
(inherited
? [...Object.keys(obj), ...Object.keys(Object.getPrototypeOf(obj))]
: Object.keys(obj)
).filter(key => typeof obj[key] === 'function');
function Foo() {
this.a = () => 1;
this.b = () => 2;
}
Foo.prototype.c = () => 3;
console.log(functions(new Foo()));
console.log(functions(new Foo(), true));
Sample Output:
["a","b"] ["a","b","c"]
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-1-47 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to perform a deep comparison between two values to determine if they are equivalent.
Next: Write a JavaScript program to retrieve a set of properties indicated by the given selectors from an object.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends
- Python Interview Questions and Answers: Comprehensive Guide
- Scala Exercises, Practice, Solution
- Kotlin Exercises practice with solution
- MongoDB Exercises, Practice, Solution
- SQL Exercises, Practice, Solution - JOINS
- Java Basic Programming Exercises
- SQL Subqueries
- Adventureworks Database Exercises
- C# Sharp Basic Exercises
- SQL COUNT() with distinct
- JavaScript String Exercises
- JavaScript HTML Form Validation
- Java Collection Exercises
- SQL COUNT() function
- SQL Inner Join