I am Hack Sparrow
Captain of the Internets.

JavaScript Array-like Objects

Have you heard about array-like objects in JavaScript? If no, this is a good post to learn about them. Array-like objects are not a separate object type, they are the same old object we are familiar with, except they 'look' like arrays. What do I mean by that? Let's find out. You might be familiar with the arguments variable which every JavaScript function has access to by default. We access its items using arguments[0], arguments[1] etc. Let's take a lo ...

JavaScript – Check Object Property is Defined

Probably you know how to check if a variable is defined in JavaScript or not (without crashing your app with a fatal ReferenceError). In case you didn't know already, here is a refresher. Wrong: [code] if (username == undefined) { console.log('username missing'); } else { console.log(username); } [/code] Right: [code] if (typeof username === 'undefined') { console.log('username missing'); ...

JavaScript – Check Object Types

There are times when you want to know the object type of an instance in JavaScript, whether it is an Array, or a Function, or an Object, a String etc. There are two flavors to doing that, one involves the use of the instanceof operator, the other involves stringification of the object's prototype. Follow the examples below, I show both the techniques. First create these variables: [code] var a = []; var o = {}; var s = ''; var n = 42; var f = function() {}; ...

Object as JavaScript object’s Key

The short answer is NO. All JavaScript object keys are strings. Even if you pass an object is a key, the object's toString() will be called on it, and the key will get the string value "[object Object]". If the above explanation did not make things obvious for you, or you in the mood for more probing, read on. You might be wondering "Hey I have used objects as keys before!". Well, it sure might have looked l ...

JavaScript: get the number of properties in an object WITHOUT LOOPING

Unlike arrays, JavaScript objects do not a have a length property which gives you the number of properties / items in an object. The most common way of getting the number of properties is to loop through the object - not pretty, resource intensive. This had been a long known problem JavaScript developers have been facing for a long time. All modern and superior browsers support a fix for this a ...