Code With Mark
Home
About
Resources
Contact

Easily Find Out The Length Of Object, Array or String

Often times you get data from many different sources. It would be helpful to know the length of the data. That would help you determine whether to go in direction A or B. Learn to easily find the length of your data whether it’s a string, object or array.

Below is a simple and easy to use JavaScript function that will help you quickly find out the size of  your data.

var size = function (collection) 
{ 
    var str = typeof(collection)

    if(str ==="number" || str ==="string")
    {
      var d1 = str.toString()
      return collection.toString().length 
    }
    else if(str ==="object" || str ==="array")
    {
      return Object.keys(collection).length
    }     
} 

Let’s suppose you have the following data:

var str = "123"
var obj = {a:2, b:2}
var arr = ["0", "1", "2",'arr']

To find out the length of each data type you would simply call it like this:

console.log( 'str -> ' + size(str) ) //--> str -> 3
console.log( 'obj -> '  + size(obj) ) //--> obj -> 2
console.log( 'arr -> ' + size(arr) ) //--> arr -> 4
 

Results for your:

  • String data, the length is only 3.
  • Object data, the length is only 2.
  • Array data, the length is only 4.

Once you start using this function, you will start to see it will make your life a lot easier.

For Web Developers

Working Hard But Still Not Getting Ahead?

You finish a project, get paid, and then it's back to finding the next client.

Month after month, the cycle repeats.

That's why many web developers never build real financial freedom—even though they're highly skilled.

The developers creating long-term wealth are using those same skills to build SaaS products, plugins, and digital tools that generate recurring income.

What if your next project could pay you more than once?

Learn How To Build Monthly Income →
Convert Your API JSON Data to HTML TableConvert Your API JSON Data to HTML Table←Previous
JavaScript Implementation Of The Secure HashJavaScript Implementation Of The Secure HashNext→

Related Posts

  • How Google Developers Think (And Why You Should Too)
  • Add Google Sign-In in 2 Minutes
  • Form Validation in 1 Line

Top Posts Viewed

Google Sheets Timesheet Website App Script
1.34K views
Learn To Create YouTube Video Downloader
1.01K views
Easily Edit HTML Table Rows Or Cells With jQuery
668 views

Categories

Courses
Excel
Google Script
Javascript
jQuery
Microsoft Access
MongoDB
Node JS
PHP
Quick Tip
Uncategorized
Wordpress