Table of contents
1.
Introduction
2.
Why This Function is Used
3.
Syntax, Parameter and Return Value
3.1.
Syntax:
3.2.
Parameters:
3.3.
Return Value: 
4.
Examples 
4.1.
Adding Logging to a Function:
4.2.
JavaScript
4.3.
Modifying Return Value:
4.4.
JavaScript
4.5.
Error Handling in Function Execution:
4.6.
JavaScript
4.7.
Performance Monitoring:
5.
Frequently Asked Questions 
5.1.
Can _.wrap() be used with methods of objects?
5.2.
Is the original function still accessible after wrapping?
5.3.
How does _.wrap() compare to subclassing or inheritance?
6.
Conclusion
Last Updated: Mar 27, 2024
Easy

Lodash _.wrap() Method

Author Riya Singh
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Enhancing or modifying the behavior of functions is a common requirement in programming, especially when you need to extend the functionality of existing code without altering it directly. Lodash's _.wrap() method offers a solution by creating a new function that provides a wrapper around the original function. 

Lodash _.wrap() Method

This allows you to execute code before and after the original function call, effectively extending its behavior.

Why This Function is Used

The _.wrap() function is used to add additional behavior to existing functions. It's particularly useful in scenarios such as logging, performance monitoring, input validation, or modifying the return value. By wrapping a function, you can add these features without modifying the original function’s source code, maintaining code integrity and reusability.

Syntax, Parameter and Return Value

Syntax:

 _.wrap(value, wrapper)

Parameters:

  • value (Function): The function to wrap.
     
  • wrapper (Function): The wrapper function.

Return Value: 

(Function) - Returns the new wrapped function.

Examples 

Adding Logging to a Function:

  • JavaScript

JavaScript

var _ = require('lodash');

function multiply(a, b) {

 return a * b;

}

var loggedMultiply = _.wrap(multiply, function(func, ...args) {

 console.log('Multiplying:', args);

 return func(...args);

});

console.log(loggedMultiply(5, 3)); // Logs 'Multiplying: [5, 3]' and outputs 15
You can also try this code with Online Javascript Compiler
Run Code

Outputs 

15


Demonstrates wrapping a function to add logging capabilities.

Modifying Return Value:

  • JavaScript

JavaScript

function greet(name) {

 return `Hello, ${name}`;

}

var excitedGreet = _.wrap(greet, function(func, ...args) {

 return func(...args) + '!!!';

});

console.log(excitedGreet('Alice'));
You can also try this code with Online Javascript Compiler
Run Code

 Outputs

 'Hello, Alice!!!'


Shows how to wrap a function to modify its return value.

Error Handling in Function Execution:

  • JavaScript

JavaScript

function riskyOperation() {

 // operation that might throw an error

}

var safeOperation = _.wrap(riskyOperation, function(func) {

 try {

   return func();

 } catch (e) {

   console.error('An error occurred:', e);

 }

});

safeOperation();
You can also try this code with Online Javascript Compiler
Run Code

// Executes the operation safely with error handling

An example of wrapping a function for added error handling.

Performance Monitoring:

function processData(data) {
  // process the data
}
var monitoredProcess = _.wrap(processData, function(func, ...args) {
  const start = performance.now();
  const result = func(...args);
  const end = performance.now();
  console.log(`Processing took ${end - start}ms`);
  return result;
});
monitoredProcess({ data: 'sample' });
You can also try this code with Online Javascript Compiler
Run Code


// Executes and logs the processing time

Demonstrates wrapping a function to monitor its performance.

Frequently Asked Questions 

Can _.wrap() be used with methods of objects?

Yes, _.wrap() can be used with object methods, allowing you to extend or modify the behavior of methods without changing the original object.

Is the original function still accessible after wrapping?

The original function is embedded within the wrapped function and is not directly accessible or modifiable from outside the wrapper.

How does _.wrap() compare to subclassing or inheritance?

_.wrap() is a functional programming approach that offers a more flexible and less intrusive alternative to subclassing or inheritance for extending functionality.

Conclusion

Lodash's _.wrap() method is a versatile tool for enhancing or altering the functionality of existing functions. It allows for the execution of additional code before or after the original function, enabling a wide range of applications from error handling to performance monitoring, without altering the original function's core logic.

You can refer to our guided paths on the Coding Ninjas. You can check our course to learn more about DSADBMSCompetitive ProgrammingPythonJavaJavaScript, etc. 

Also, check out some of the Guided Paths on topics such as Data Structure and AlgorithmsCompetitive ProgrammingOperating SystemsComputer Networks, DBMSSystem Design, etc., as well as some Contests, Test Series, and Interview Experiences curated by top Industry Experts.

Live masterclass