I’m working my way through JavaScript: The Good Parts
, and as I come across things I’m not familiar with myself, I’m sharing it. My hope is that some of my findings perk the interest of anyone who reads it and gets them to dive a bit deeper into JavaScript as well.
While reading about objects, Crockford describes the process of retrieving object values and assigning them to variable. While he didn’t specifically outline that this is a performance benefit, I’m pretty sure it is, since you wouldn’t have to “lookup” the value each time and could simply refer to the variable which holds that objects value.
Moving on, let’s say we have the following object:
var myObj = {
foo: 'fu'
};
To assign myObj.foo to a variable, there’s nothing complicated or tricky, it’s exactly what one would think:
var myFoo = myObj.foo; // 'fu'
So far, so good…but what if you hadn’t set the value of myObj.foo or wanted to set a variable according to another property of myObj, that may not have been defined yet? Well, it turns out that there’s a nice way to do this using OR (||).
For this example, we use myObj.bar which is undefined.Since we do in fact want to set it to something, we’ll test to see if it has been set, and if it hasn’t we’ll set a default value:
var myBar = myObj.bar || 'bar'; // if undefined set to 'bar';
And there you have it…it’s as simple as that. Pretty slick, eh?
This being my first time encountering it, I thought it was clever. Hopefully you’ll be able to find some usefulness for it in your own code, slimming down on some of the “uglier” ways this can be done. Enjoy.
