Lodash - Environment Setup



In this chapter, you will learn in detail about setting up the working environment of Lodash on your local computer. Before you begin with working on Lodash, you need to have the access to the library. You can access its files in any of the following methods −

Method 1: Using Lodash File in Browser

In this method, we are going to need Lodash file from its official website and will use it directly in the browser.

Step 1

As a first step, go to the official website of Lodash https://lodash.com/.

Observe that there is a download option available which gives you the latest lodash.min.js file CDN Copies available. Click on the link and select latest link for lodash.min.js.

Step 2

Now, include lodash.min.js inside the script tag and start working with Lodash. For this, you can use the code given below −

<script type = "text/JavaScript" 
   src = "https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js">
</script>

Given here is a working example and its output for a better understanding −

Example

<html>
   <head>
      <title>Lodash - Working Example</title>
      <script type = "text/JavaScript" src = "https://cdn.jsdelivr.net/npm/lodash@4.17.20/lodash.min.js"></script>
      <style>
         div {
            border: solid 1px #ccc;
            padding:10px;
            font-family: "Segoe UI",Arial,sans-serif;
            width: 50%;
         }
      </style>
   </head>
   <body>
      <div style = "font-size:25px" id = "list"></div>
      <script type = "text/JavaScript">
         var numbers = [1, 2, 3, 4];
         var listOfNumbers = '';
         _.each(numbers, function(x) { listOfNumbers += x + ' ' });
         document.getElementById("list").innerHTML = listOfNumbers;
      </script>
   </body>
</html>

Output

Method 2: Using Node.js

If you are opting for this method, make sure you have Node.js and npm installed on your system. You can use the following command to install Lodash −

npm install lodash

You can observe the following output once Lodash is successfully installed −

+ lodash@4.17.20
added 1 package from 2 contributors and audited 1 package in 2.54s
found 0 vulnerabilities

Now, to test if Lodash works fine with Node.js, create the file tester.js and add the following code to it −

var _ = require('lodash');
var numbers = [1, 2, 3, 4];
var listOfNumbers = '';
_.each(numbers, function(x) { listOfNumbers += x + ' ' });
console.log(listOfNumbers);

Save the above program in tester.js. The following commands are used to compile and execute this program.

Command

\>node tester.js

Output

1 2 3 4
Advertisements