Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does [] mean in JavaScript?

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

var openTollDebug = []; 
like image 202
Wiika Avatar asked Feb 17 '10 11:02

Wiika


People also ask

What is the difference between [] and {} in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

Why [] == [] is false in JavaScript?

The reason for [] == false even though [] is truthy is: the comparison [] == false compares the value of [] to false . And to get the value of [] , the JavaScript engine first calls []. toString() . That results in "" , and that is what's actually compared to false .

Whats the difference between {} and [] in array?

[] is declaring an array. {} is declaring an object. An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class.

What are square brackets used for in JavaScript?

The [] operator converts the expression inside the square brackets to a string. For instance, if it is a numeric value, JavaScript converts it to a string and then uses that string as the property name, similar to the square bracket notation of objects to access their properties.


2 Answers

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] 
like image 188
Russ Cam Avatar answered Sep 21 '22 20:09

Russ Cam


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' 
like image 36
Darin Dimitrov Avatar answered Sep 20 '22 20:09

Darin Dimitrov