views:

169

answers:

6

In the following javascript code there is [] being assigned as the value of a variable, what does it mean?

var openTollDebug = [];
+5  A: 

It means an array.

var openTollDebug = [];

declares the openTollDebug variable and initializes it to an empty array. To put elements into the array you could do the following:

var stringArray = ['element1', 'element2', 'element3'];
alert(stringArray[1]); // displays 'element2'
var numberArray = [1, 2, 3, 4];
alert(numberArray[2]); // displays 3
var objectArray = [{ name: 'john' }, { name: 'peter' }, { name: 'tom' }];
alert(objectArray[1].name); // displays 'peter'
Darin Dimitrov
+15  A: 

it is an array literal. It is not quite the same as declaring new Array() - the Array object can be overwritten in JavaScript, but the array literal can't. Here's an example to demonstrate

// let's overwrite the Array object
Array = function(id) {
 this.id = id;
}

var a = new Array(1);
var b = [];

console.log(a.hasOwnProperty("id")); // true
console.log(b.hasOwnProperty("id")); // false

console.log(a.push); // false, push doesn't exist on a
console.log(b.push); // true,  but it does on b

b.push(2);
console.log(b); // outputs [2]
Russ Cam
Ooh, nice verbiage!
Timothy Khouri
So long as `Array` hasn't been overwritten, `new Array()` and `[]` are functionally identical.
Tim Down
@Tim - yes they are. There is also a difference in intializing values and length - `new Array(5)` is not the same as `[5]` :)
Russ Cam
for the person who gave the -1 : why? I believe I qualified that declaring `[]` and `new Array()` is not quite the same as the latter is based on the condition that `Array` has not been overwritten.
Russ Cam
+6  A: 

It's an empty array, and is equal to


var openTollDebug = new Array();

simon
+3  A: 

It is shorthand for empty array. Same as new Array(). Also {} is an empty object. Objects are like hashtables in Js so you can use it as a dictionary.

Ekin Koc
+2  A: 

It creates an empty array.
This is a good way to have a non-null object.
In JavaScript, it is then very easy to add functions and properties to that object. For example:

openTollDebug.title = 'hello world';
openTollDebug.show = function(){alert('Debug');};

As an array, you can add items:

openTollDebug.push('added item');
openTollDebug[3] = 'just add anywhere';
Kobi
+1  A: 

Many languages have constructs for literals. The [] is an Array literal.

var openTollDebug = [];

is the same as

var openTollDebug = new Array();

Just know that using [] preferred for performance reasons.

There are other literals like Object literals

var MyObject = {
              name:'default',
              age:22,
              hobbies:["golf","video games","otherstuff"]
}

Notice the array literal with data. The [] creates an empty array.

Tone