Javascript array/object shortcuts

I always forget the syntax to make a new object or array in Javascript.

var my_array = new Array();

Or you can simplify the whole process:

var my_array = [1,2,3];

This is the syntax to make a new Object (hash) in Javascript:

var my_obj = new Object();
my_obj['foo'] = 'bar';
my_obj['apple'] = 'red';

But can be shortened this way:

var my_obj = { 'foo':'bar' , 'apple':'red' }

Just remember that arrays are initialized with [] and objects are initialized with {}. This is the same syntax as Perl's array and hash references.

Leave A Reply
All content licensed under the Creative Commons License