how to use the size function from lodash in javascript

To use the size function from lodash in JavaScript, first, we need to install the lodash library using npm.

npm i lodash
13 chars
2 lines

After installing the lodash library, we can use the size function to get the length of the object or the number of elements in an array/collection.

index.tsx
const _ = require('lodash');

const obj = {a: 1, b: 2, c: 3};
console.log(_.size(obj)); // Output: 3

const arr = [1,2,3,4,5];
console.log(_.size(arr)); // Output: 5

const str = 'hello';
console.log(_.size(str)); // Output: 5

const emptyObj = {};
console.log(_.size(emptyObj)); // Output: 0

const nullVal = null;
console.log(_.size(nullVal)); // TypeError: Cannot convert null or undefined to object
403 chars
17 lines

In the above code, we have imported/required the lodash library and used the size function to get the size of different objects, including the array, object, and string. We have also handled the case when the input is undefined or null.

gistlibby LogSnag