Skip to content
barrydorman edited this page Jun 16, 2012 · 6 revisions

Using Associative Arrays

Did you know JavaScript objects are also associative arrays? That's a fancy term for what people in the .NET world might just call a Dictionary. For example, given an object x, you can get or set the value of a field on x by either accessing the field directly, x.field = 'hi'; or by accessing the field using a string key, such as x['field'] = 'hi';. So why am I telling you this? Because, the base Object type defined in Blade supports this concept. This means you can dynamically access fields (or methods for that matter) on any object. This opens up some additional flexibility inherent in JavaScript, but also comes with some responsibility, as it could easily be abused. Just don't get too carried away.


Checking for Undefined

If you have a C# background, you're probably aware that objects have a predictable initial value. That is, any reference type is initialized to null, integer types are initialized to 0, etc. In JavaScript however, if you attempt to access anything that hasn't been explicitly initialized you'll get back the value undefined. Did you know the undefined value is actually just a global static object? In Blade you can access it like this: window.undefined. It's also setup as a dynamic value, allowing you to compare it against anything. By default Blade initializes values to what you'd expect for class members. Reference types are set to null, and value types are set accordingly. This isn't the case for all declarations though. For example, it isn't feasible for Blade to assume it can initialize all elements of an array (this could be costly). So if you ever want to compare something for null or undefined, you could do this: if(obj == null || obj == window.undefined). Those of you more familiar with JavaScript may note you can get the same effect just using if(!obj). There are some caveats, but in general this is true. You could pull this off in Blade by casting to dynamic prior to comparison. For example, if(!(dynamic)obj). Eventually I'd like to see these sorts of JavaScript idioms become post processes of the compiler.

Clone this wiki locally