Introduction
In this lab, we will explore the implementation of a JavaScript function that determines the size of an array, object, or string. Through this lab, you will learn how to identify the type of a given value and determine its size using various techniques such as the Array.prototype.length property, the length or size value, and the number of keys for objects. By the end of this lab, you will have a better understanding of how to work with different data types in JavaScript.
Function to Get Size of Array, Object, or String
To use this function, open the Terminal/SSH and type node. This function gets the size of an array, object or string.
To use it:
- Determine the type of
val(array,objectorstring). - Use the
Array.prototype.lengthproperty for arrays. - Use the
lengthorsizevalue if available, or the number of keys for objects. - For strings, use the
sizeof aBlobobject created fromval.
const size = (val) =>
Array.isArray(val)
? val.length
: val && typeof val === "object"
? val.size || val.length || Object.keys(val).length
: typeof val === "string"
? new Blob([val]).size
: 0;
Examples:
size([1, 2, 3, 4, 5]); // 5
size("size"); // 4
size({ one: 1, two: 2, three: 3 }); // 3
Summary
Congratulations! You have completed the Size of Array, Object or String lab. You can practice more labs in LabEx to improve your skills.