Arrays - jpjohnsonjr/learning-notes GitHub Wiki
About
Javascript is different from other languages in that it allows "dynamic typing" in arrays, meaning that objects of different types can be stored in the same array. Take for example the following code:
2 var array = new Array();
3 array[0] = "Yaakov";
4 array[1] = 2;
5 array[2] = function (name) {
6 console.log("Hello " + name) {
7 };
8 array[3] = {course: " HTML, CSS & JS");
9
10 console.log(array);
From the above, we can see the following reflected in the console output:
- Line 3: The first position of the array (0) contains a string,
"Yaakov" - Line 4: The second position (1) contains a numeral,
2 - Line 5: The third position (2) contains a function
- Line 8: The fourth position (3) contains an object
Creating Arrays Using Shorthand Notation
Here's an example:
16 var names = [];
The empty brackets creates an array. Values can also be instantly assigned to each position in the array in a comma-separated list:
16 var names = ["Yaakov", "John", "Joe"];
Looping Over an Array
Here's a loop using the array declared above as Line 16:
19 for (var i = 0; i < names.length; i++) {
20 console.log ("Hello " + names[i])
21 };
Above, names.length references a default property of an array, length, defined by the number items in the array. As the loop operates, the [i] after names will cause the output to use each of the values in the array in turn.
Note that in Javascript, arrays can be "sparse," meaning that they can have gaps at different positions where no value is assigned for example, for the above code, we could add names[100] = "Jim", and this would be allowable. Positions 3 through 99 would output as undefined, but Jim would output when the loop got to 100. The value of name.length would be extended automatically.
An Issue with for Loops and Arrays
An issue arises when using a for loop on an object literal. Consider the following:
42 var names2 = ["Yaakov", "John", "Joe"];
43 names2.greeting = "Hi!";
44
45 for (var name in names2) {
46 console.log("Hello " + names2[name]);
47 }
This will output Yaakov,John,Joe, and Hi! because the property in an object literal that is an array is simply counted as another value in the array.