Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
What is the use of _.size() method in JavaScript?
The _.size() method is part of the Underscore.js library and returns the number of elements in arrays, objects, and strings. It provides a consistent way to get the size of various data types.
Syntax
_.size(collection)
Parameters
collection: The array, object, or string to count elements from.
Return Value
Returns a number representing the count of elements in the collection.
Example 1: Array Size
Find the size of a numeric array using _.size():
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
var arr = [100, 62, 73, 534, 565];
document.write("Array size: " + _.size(arr));
</script>
</body>
</html>
Array size: 5
Example 2: Array of Objects
Count elements in an array containing objects:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
var arr = [
{name: "Anu", age: 25},
{name: "Uday", age: 29},
{name: "Anusha", age: 23}
];
document.write("Objects count: " + _.size(arr));
</script>
</body>
</html>
Objects count: 3
Example 3: Object Properties
Count properties in an object:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
var obj = {name: "John", age: 30, city: "New York"};
document.write("Object properties: " + _.size(obj));
</script>
</body>
</html>
Object properties: 3
Example 4: String Length
Get the length of a string:
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
</head>
<body>
<script type="text/javascript">
var str = "JavaScript";
document.write("String length: " + _.size(str));
</script>
</body>
</html>
String length: 10
Comparison with Native Methods
| Data Type | Native Method | _.size() |
|---|---|---|
| Array | arr.length |
_.size(arr) |
| Object | Object.keys(obj).length |
_.size(obj) |
| String | str.length |
_.size(str) |
Conclusion
_.size() provides a unified way to count elements across different data types. While native methods exist for specific types, Underscore.js offers consistency for mixed-type scenarios.
Advertisements
