Understanding Javascript : Array



imagine if you have 5 data, then you would like to assign variable for each data to hold it's value:

var apple     = "apple";
var orange    = "orange";
var pineapple = "pineapple";
var jackfruit = "jackfruit";
var mango     = "mango";


this is ineffective, the other way to hold more data in just one variable, is called "array".
Array is a 'container' to hold data, you can fill the array with variety of data-types, integer, strings, float, double, or even a boolean.


the example of an array is like this :
var fruits = ["orange", "pineapple", "jackfruit", "mango"];

explanation :
var arrayName = ["string is double-quoted like this", 'or you can use single quote', true //boolean doesn't need quotes ,1234 //integer also doesn't need it ];


creating the array is just like creating a variable, just start with var keyword, follow with the name, and equal sign, here array uses square bracket to wrap the datas, and use comma to separate the datas.

array is having index for each of its data. but the index start from zero, so if you want to print out the "orange" value from fruits array, you could type : 


console.log(fruits[0]);

fruits is the name of the array, [0] is the array-index that you want to print.


and you can also insert a data into an array, like this :


var anArray = [];
anArray.push("katana");
console.log(anArray);
//will output ["katana"]

using the .push(); method to push data into the array, insert data you want to insert into the array inside the parentheses beside 'push'. example above is how to insert "katana" string into the anArray array, then print it out.


You can remove data from an array, using the .pop(); method :


var anArray = ["katana", "gun", "m4a1"];
anArray.pop();
console.log(anArray);
//will output ["katana", "gun"]

.pop(); (without anything inside the parentheses) is a method to remove the last data from an array. so if we do anArray.pop();, it will remove the last data of the array, so it will output only "katana" and "gun".
Previous
Next Post »