What does [] mean in JavaScript?
Solution 1
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]
Solution 2
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'
Solution 3
It's an empty array, and is equal to
var openTollDebug = new Array();
Solution 4
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.
Solution 5
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';
Related videos on Youtube
Wiika
Updated on July 09, 2022Comments
-
Wiika almost 2 years
In the following javascript code there is
[]
being assigned as the value of a variable, what does it mean?var openTollDebug = [];
-
Tim Down about 14 yearsSo long as
Array
hasn't been overwritten,new Array()
and[]
are functionally identical. -
Russ Cam about 14 years@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 about 14 yearsfor the person who gave the -1 : why? I believe I qualified that declaring
[]
andnew Array()
is not quite the same as the latter is based on the condition thatArray
has not been overwritten. -
Quaternion about 12 yearsYou should check to see if there are answers which already provide the same information.
-
Pacerier over 6 years@RussCam, So how do we override
[]
constructor?