JavaScript: Create a function that invokes fn with a given context
JavaScript fundamental (ES6 Syntax): Exercise-59 with Solution
Write a JavaScript program to create a function that invokes fn in a given context. Optionally add any additional variables to the arguments beginning.
- Return a function that uses Function.prototype.apply() to apply the given context to fn.
- Use the spread operator (...) to prepend any additional supplied parameters to the arguments.
Sample Solution:
JavaScript Code:
//#Source https://bit.ly/2neWfJ2
const bind = (fn, context, ...args) =>
function() {
return fn.apply(context, args.concat(...arguments));
};
function greet(greeting, punctuation) {
return greeting + ' ' + this.user + punctuation;
}
const freddy = { user: 'Morning' };
const freddyBound = bind(greet, freddy);
console.log(freddyBound('Good', '!'));
Sample Output:
Good Morning!
Flowchart:

Live Demo:
See the Pen javascript-basic-exercise-59-1 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus
Previous: Write a JavaScript program to split values into two groups according to a predicate function, which specifies which group an element in the input collection belongs to.
Next: Write a JavaScript program to create a function that invokes the method at a given key of an object, optionally adding any additional supplied parameters to the beginning of the arguments.
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