Arieh.co.il

Introduction to $count

This is a small article about a simple function I uploaded to the Forge - $count. What this function does is to supply a cross-type interface to figure out the size of a variable. Javascript has only a limited number of types that contain the length attribute, such as String and Array. But many dont', such as associative arrays - aka literal objects - don't.

There are many cases when I would like to find out the length of the element, but for each type there is a different method. For an Object, i would do:

$H(obj).length;

Also, there are many times where the main test we want to check for is wheather a variable is empty or not. For this porpose, I decided to create a small function that will take any type of a variable and will try to enumerate it. At a minimum, it will do it's best to find out wheather a variable is empty or not.

For now, these variable types are supported:

  1. Number will return the number.
  2. String will return the string's length.
  3. Object will return the number of variables and methods attached to the object.
  4. Function will return whether the function is empty or not.
  5. DOM elements (window, document and Element) will return the number of children the element contains
  6. Boolean 1 for true, 0 for false.
  7. For all others At first it will check if a length property exsits. If not, it will attempt to enumerate the variable (using the var operator). If failed, it will fallback to return 1 (the default assums non-empty to make sure if statements won't break).

Use cases:

Well, I find it mostly usefull when I don't want to remind myself the best way to findout how to determine a var's length. In particular - this is the best and simplest way to find out whether a Function is empty of not (===$empty doesn't work). As it is very small (1KB minified) it is quite harmfull in the long run.

Links

  1. Forge Page.
  2. Github Page.
JavaScript Reference, JavaScript Guide, JavaScript API, JS API, JS Guide, JS Reference, Learn JS, JS Documentation