0
# lodash.size
1
2
Gets the size of collections by returning the length for array-like values or the number of own enumerable properties for objects. This is a modularized build of lodash's `_.size` method, exported as a standalone Node.js module.
3
4
## Package Information
5
6
- **Package Name**: lodash.size
7
- **Package Type**: npm
8
- **Language**: JavaScript
9
- **Installation**: `npm install lodash.size`
10
11
## Core Imports
12
13
```javascript
14
var size = require('lodash.size');
15
```
16
17
For modern environments supporting ES modules:
18
19
```javascript
20
import size from 'lodash.size';
21
```
22
23
## Basic Usage
24
25
```javascript
26
var size = require('lodash.size');
27
28
// Array size
29
size([1, 2, 3]);
30
// => 3
31
32
// Object size (number of own enumerable properties)
33
size({ 'a': 1, 'b': 2 });
34
// => 2
35
36
// String size
37
size('pebbles');
38
// => 7
39
40
// Null/undefined handling
41
size(null);
42
// => 0
43
44
size(undefined);
45
// => 0
46
47
// Empty values
48
size([]);
49
// => 0
50
51
size({});
52
// => 0
53
54
size('');
55
// => 0
56
```
57
58
## Capabilities
59
60
### Size Calculation
61
62
Gets the size of a collection by returning its length for array-like values or the number of own enumerable properties for objects.
63
64
```javascript { .api }
65
/**
66
* Gets the size of collection by returning its length for array-like
67
* values or the number of own enumerable properties for objects.
68
*
69
* @param {Array|Object|string} collection The collection to inspect.
70
* @returns {number} Returns the size of collection.
71
*/
72
function size(collection)
73
```
74
75
**Parameters:**
76
- `collection` (Array|Object|string): The collection to inspect
77
78
**Returns:**
79
- (number): The size of collection
80
81
**Behavior:**
82
- For arrays and array-like objects (with numeric `length` property): returns the `length` value
83
- For objects: returns the count of own enumerable properties (uses `lodash.keys` internally)
84
- For strings: returns the string length
85
- For `null` or `undefined`: returns `0`
86
- For values with invalid length properties: falls back to counting object properties
87
88
**Examples:**
89
90
```javascript
91
// Arrays
92
size([1, 2, 3, 4, 5]);
93
// => 5
94
95
// Array-like objects
96
size({ 0: 'a', 1: 'b', 2: 'c', length: 3 });
97
// => 3
98
99
// Plain objects
100
size({ foo: 'bar', baz: 'qux' });
101
// => 2
102
103
// Strings
104
size('hello world');
105
// => 11
106
107
// Edge cases
108
size(null); // => 0
109
size(undefined); // => 0
110
size([]); // => 0
111
size({}); // => 0
112
size(''); // => 0
113
114
// Objects with length property that isn't valid
115
size({ length: 'invalid', a: 1, b: 2 });
116
// => 2 (counts properties, ignores invalid length)
117
```