Introduction to Lodash Library in ServiceNow

DINESH KUMAR15
Tera Contributor

The Lodash library is a versatile utility library that provides a wide range of functions for simplifying common tasks in JavaScript. ServiceNow developers can leverage Lodash to enhance their code quality, improve performance, and streamline development. Here are some key points to consider:

 

  1. What Is Lodash?

    • Lodash is a popular JavaScript library that offers utility functions for arrays, objects, strings, and more.
    • It provides consistent and efficient methods for common operations, making code more readable and maintainable.
  2. Features and Benefits:

    • Chaining Methods: Lodash allows you to chain multiple methods together, creating expressive and concise code. For example:
      var users = [
      { 'user': 'barney', 'age': 36 },
      { 'user': 'fred', 'age': 40 },
      { 'user': 'pebbles', 'age': 1 }
      ];

      var youngest = _
      .chain(users)
      .sortBy('age')
      .map(function(o) {
      return o.user + ' is ' + o.age;
      })
      .head()
      .value();
      // => 'pebbles is 1'
    • Functional Helpers: Lodash provides functions inspired by functional programming paradigms. Use filter, map, reduce, and others to manipulate arrays efficiently.
    • String Manipulation: Lodash simplifies string handling tasks, such as capitalization, trimming, and substring replacement.
  3. Use Cases for Lodash in ServiceNow:

    • Script Includes: Incorporate Lodash functions into custom script includes. Optimize GlideRecord queries or process data seamlessly.
    • Business Rules and Workflows: Enhance business rules and workflows by leveraging Lodash’s features. Handle arrays, perform transformations, and simplify logic.
    • Client Scripts: Improve client-side scripts by using Lodash for array manipulation, string operations, and other common tasks.
    • Widget: This can only be used in client script in the widget.
  4. Getting Started with Lodash:

    • Include the Library: Ensure that Lodash is available in your ServiceNow instance. You can use the built-in Lodash module or import it externally.
    • Explore Documentation: Refer to the Lodash documentation for more examples/syntax.

Conclusion

Lodash is a valuable asset for ServiceNow developers, offering a robust set of tools to simplify development tasks. As you explore its capabilities, you’ll find creative ways to enhance your ServiceNow applications. Happy coding!

 

 

Hope, this will be helpful.

 

Regards,

A Dinesh Kumar

LinkedIn: https://www.linkedin.com/in/a-dinesh-kumar

 

#LearnTogether #RiseUp #CodingTips

4 REPLIES 4

saurabh_dubey
Kilo Sage

Update...

 

You can use lodash.js directly in servicePortal (widget editor) scripts.

 

Thanks

Saurabh Dubey.

Hi @saurabh_dubey ,

 

Yes but not all scripts, only in client-script in the widget editor, As mentioned in 3rd point -> Widget.
You can't use it in server-script.

VaranAwesomenow
Mega Sage

I ran this via fix script and I keep getting syntax error may be am missing something.

VaranAwesomenow_0-1737474151103.png

 

Hi @VaranAwesomenow ,

 

Unlike client scripts, you cannot use Lodash directly in fix scripts. To use Lodash in a fix script, you must manually load its functions. Below is an example.

var LodashScriptInclude = Class.create();
LodashScriptInclude.prototype = {
    initialize: function() {
        // Lodash functions example
        this._ = {
            chunk: function(array, size) {
                size = Math.max(size, 0);
                const length = array == null ? 0 : array.length;
                if (!length || size < 1) {
                    return [];
                }
                let index = 0;
                let resIndex = 0;
                const result = new Array(Math.ceil(length / size));
                while (index < length) {
                    result[resIndex++] = array.slice(index, (index += size));
                }
                return result;
            },
            sortBy: function(array, iteratees) {
                if (array == null) {
                    return [];
                }
                let index = -1;
                iteratees = this.baseFlatten(iteratees, 1);
                const length = array.length;
                const result = new Array(length);
                while (++index < length) {
                    result[index] = array[index];
                }
                return this.baseOrderBy(result, iteratees);
            },
            baseFlatten: function(array, depth) {
                const result = [];
                if (array == null) {
                    return result;
                }
                this.baseFlattenInternal(array, depth, result);
                return result;
            },
            baseFlattenInternal: function(array, depth, result) {
                let index = -1;
                const length = array.length;
                while (++index < length) {
                    const value = array[index];
                    if (Array.isArray(value) && depth > 0) {
                        this.baseFlattenInternal(value, depth - 1, result);
                    } else {
                        result.push(value);
                    }
                }
            },
            baseOrderBy: function(array, iteratees) {
                // Simplified version for example purposes
                return array.sort((a, b) => {
                    for (let i = 0; i < iteratees.length; i++) {
                        if (a[iteratees[i]] > b[iteratees[i]]) return 1;
                        if (a[iteratees[i]] < b[iteratees[i]]) return -1;
                    }
                    return 0;
                });
            }
        };
    },

    // Example method using Lodash functions
    exampleMethod: function() {
        var users = [
            { 'user': 'barney', 'age': 36 },
            { 'user': 'fred', 'age': 40 },
            { 'user': 'pebbles', 'age': 1 }
        ];
        var youngest = this._.sortBy(users, ['age'])[0];
        gs.info(youngest.user + ' is ' + youngest.age); // => 'pebbles is 1'
    },

    type: 'LodashScriptInclude'
};