Size of Array, Object or String

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28616{{"`Size of Array, Object or String`"}} javascript/data_types -.-> lab-28616{{"`Size of Array, Object or String`"}} javascript/arith_ops -.-> lab-28616{{"`Size of Array, Object or String`"}} javascript/comp_ops -.-> lab-28616{{"`Size of Array, Object or String`"}} javascript/destr_assign -.-> lab-28616{{"`Size of Array, Object or String`"}} end

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, object or string).
  • Use the Array.prototype.length property for arrays.
  • Use the length or size value if available, or the number of keys for objects.
  • For strings, use the size of a Blob object created from val.
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.

Other JavaScript Tutorials you may like