What does [] mean in JavaScript? - javascript

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

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]

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'

It's an empty array, and is equal to
var openTollDebug = new Array();

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.

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';

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.

Try to use literals due to performance. You dont write
var obj = new Object({name: 'John'})
You just write
var obj = {name: 'John'}
You also dont write
button.onclick = new Function("alert('Clicked!')");
You write
button.onclick = function () { alert('Clicked') }
And here's a link to a nice blog post about it

var b = [] //it is an array literal.

Related

JSON stringify does not convert array [duplicate]

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

Why does a string index in an array not increase the 'length'?

In the example below, the array2.length is only 10, while in my mind, it should be 13.
Why does the "string keyed" indexes not increase the length of the array?
I can store things and still access it, and the VS debugger shows that those arrays are being stored properly. So why is the length not increased?
var array2 = new Array();
array2["a"] = new Array();
array2["b"] = new Array();
array2["c"] = new Array();
for (var i = 0; i < 10; ++i)
array2[i] = new Array();
var nothing = "";
for (var i = 0; i < array2.length; ++i)
nothing = "";
Javascript arrays cannot have "string indexes". A Javascript Array is exclusively numerically indexed. When you set a "string index", you're setting a property of the object. These are equivalent:
array.a = 'foo';
array['a'] = 'foo';
Those properties are not part of the "data storage" of the array.
If you want "associative arrays", you need to use an object:
var obj = {};
obj['a'] = 'foo';
Maybe the simplest visualization is using the literal notation instead of new Array:
// numerically indexed Array
var array = ['foo', 'bar', 'baz'];
// associative Object
var dict = { foo : 42, bar : 'baz' };
Because the length is defined to be one plus the largest numeric index in the array.
var xs = [];
xs[10] = 17;
console.log( xs.length ); //11
For this reason, you should only use arrays for storing things indexed by numbers, using plain objects instead if you want to use strings as keys. Also, as a sidenote, it is a better practice to use literals like [] or {} instead of new Array and new Object.
You're not adding items to the array; you're adding properties to the Array object.
As said above, use object for associative arrays.
If you don't you won't necessarily notice you're doing it wrong, until you innocently use "length" as an array index :
var myArray = [];
myArray["foo"] = "bar"; //works
console.log(myArray["foo"]) //print "bar"
myArray["length"] = "baz" //crash with a "RangeError: Invalid array length"
That is because you are replacing the length attribute of an array with a String, which is invalid.
"string keyed" indexes are not indexes at all, but properties. array2["a"] is the same as saying array2.a. Remember that you can set properties on any kind of variable in javascript, which is exactly what you're doing here.
You can push object to array, it will automatically get indexed (integer). If you want to add index as you want then you want to make it as object
If you want to use an object's properties as if they were like instances of a string indexed array, the work around for the length is:
var myArray = new Array();
myArray["a"] = 'foo';
myArray["b"] = 'bar';
myArray["c"] = 'baz';
let theLength = Object.keys(myArray).length

javascript push multidimensional array

I've got something like that:
var valueToPush = new Array();
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
the result is [];
what am i do wrong?
Arrays must have zero based integer indexes in JavaScript. So:
var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);
Or maybe you want to use objects (which are associative arrays):
var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);
which is equivalent to:
var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.
Use []:
cookie_value_add.push([productID,itemColorTitle, itemColorPath]);
or
arrayToPush.push([value1, value2, ..., valueN]);
In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.
Instead, declare valueToPush as an object and push that onto cookie_value_add:
// Create valueToPush as an object {} rather than an array []
var valueToPush = {};
// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);
// View the structure of cookie_value_add
console.dir(cookie_value_add);

declare hashmap in javascript with <String,String array>

I want to declare a hashmap in javascript with <String, String array> instead of <String,Integer>. How can that be done ?
If you plan to use a javascript Array object, be aware that an array index can only be accessed via integers.
var arr = [];
arr['person'] = 'John Smith';
alert(arr.length); // returns 0, not an array anymore;
and
var arr = [];
arr[0] = 'John Smith';
alert(arr.length); // returns 1, still an array;
The above would work in javascript, but var arr actually is not an array object anymore. You cannot sort it, for example.
So for you hashmap you could do
var map = new Object();
map['person'] = [];
map['person']['test'] = 'myvalue';
map['person']['test2'] = 'myvalue2';
alert(map['person']['test']);

JavaScript push to array

How do I push new values to the following array?
json = {"cool":"34.33","alsocool":"45454"}
I tried json.push("coolness":"34.33");, but it didn't work.
It's not an array.
var json = {"cool":"34.33","alsocool":"45454"};
json.coolness = 34.33;
or
var json = {"cool":"34.33","alsocool":"45454"};
json['coolness'] = 34.33;
you could do it as an array, but it would be a different syntax (and this is almost certainly not what you want)
var json = [{"cool":"34.33"},{"alsocool":"45454"}];
json.push({"coolness":"34.33"});
Note that this variable name is highly misleading, as there is no JSON here. I would name it something else.
var array = new Array(); // or the shortcut: = []
array.push ( {"cool":"34.33","also cool":"45454"} );
array.push ( {"cool":"34.39","also cool":"45459"} );
Your variable is a javascript object {} not an array [].
You could do:
var o = {}; // or the longer form: = new Object()
o.SomeNewProperty = "something";
o["SomeNewProperty"] = "something";
and
var o = { SomeNewProperty: "something" };
var o2 = { "SomeNewProperty": "something" };
Later, you add those objects to your array: array.push (o, o2);
Also JSON is simply a string representation of a javascript object, thus:
var json = '{"cool":"34.33","alsocool":"45454"}'; // is JSON
var o = JSON.parse(json); // is a javascript object
json = JSON.stringify(o); // is JSON again
That is an object, not an array. So you would do:
var json = { cool: 34.33, alsocool: 45454 };
json.supercool = 3.14159;
console.dir(json);
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
Object vs Array: JavaScript
Use the push() function to append to an array:
// initialize array
var arr = [
"Hi",
"Hello",
"Bonjour"
];
// append new value to the array
arr.push("Hola");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
];
// append multiple values to the array
arr.push("Salut", "Hey");
Now array is
var arr = [
"Hi",
"Hello",
"Bonjour"
"Hola"
"Salut"
"Hey"
];
// display all values
for (var i = 0; i < arr.length; i++) {
console.log(arr[i]);
}
Will print:
Hi
Hello
Bonjour
Hola
Salut
Hey
Update
If you want to add the items of one array to another array, you can use Array.concat:
var arr = [
"apple",
"banana",
"cherry"
];
arr = arr.concat([
"dragonfruit",
"elderberry",
"fig"
]);
console.log(arr);
Will print
["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]

Categories