JavaScript shortcut notations that shouldn’t be black magic to the “average developer”

When publishing articles about JavaScript development you run into many rules set by publishers and editors. This is a great thing as it keeps us authors on our toes and makes us understand more about how much work successful publishing really is. However, it can also be terribly annoying, especially when older idioms just stick. One of them is that “the average developer” does not quite understand JavaScript shortcut notations. Now, if you are “the average developer”, please give me 5 minutes of your time to get through the following, you’ll understand a lot more code out there and also spend a lot less time writing your own scripts.

Array shortcut notation – It is hip to be square

The first bugbear I have are arrays. These are terribly useful and omnipresent in JavaScript and still I find people who write convoluted things like:

var links = new Array();
links[0] = 'http://cuteoverload.com';
links[1] = 'http://icanhascheezburger.com';
links[2] = 'http://pencilsatdawn.wordpress.com';
links[3] = 'http://apelad.blogspot.com';
// ... ad nauseam ...

This is convoluted (you have to repeat the array name for every item) and also tricky to maintain. When you change the order (granted the order is of importance) you need to change the number, too. It is not necessary, as the numbering is done automatically for you. All you need to do is use the square brackets:

var links = [
'http://cuteoverload.com',
'http://icanhascheezburger.com',
'http://pencilsatdawn.wordpress.com',
'http://apelad.blogspot.com' // commatacommas (Happy, Stuart?) (except for the last one which you need to omit) and the equal signs become colons. If the properties (the things to the left of the colon) don’t have any spaces in them, you can even get rid of the quotes:
```javascript

var chris = { hair : 'red', age : 32, city : 'London' }

You can access the properties with object.property when they don’t have any spaces or with object[property] when they have spaces. For example: ```javascript

var links = { ‘Cute Overload’ : ‘http://cuteoverload.com’, ‘I can has cheeseburger’ : ‘http://icanhascheezburger.com’, ‘Pencils at dawn’ : ‘http://pencilsatdawn.wordpress.com’, ‘Hobotopia’ : ‘http://apelad.blogspot.com’ //

Tags: bestpractice, code, default, javascript, learningjavascript, objectliteral, style, syntax, ternary, webdevtrick