Javascript – Arrays

An array is a container with an index that you can store in many values. You can declare an array:

var persons = [];

The above is an empty array. You can also declare an array with its values

var persons = ["Kronos", "Zeus", "Ira"];

You can access an array element using indexes, starting from 0

console.log(persons[1]); //will print Zeus

You can change the value of an array using indexes:

persons[2] = "Afroditi";
, <span>Javascript – Arrays</span>, KandZ

, <span>Javascript – Arrays</span>, KandZ

Arrays are objects. That means they have methods and properties which you can access using the “.” .

console.log(typeof persons);
, <span>Javascript – Arrays</span>, KandZ

You can add a new element at the end using push() method

personts.push("Ira");

and you can delete the last element using pop() method;

persons.pop()

length returns the size of the array. sort() sorts the array. splice(startingIndex, amount) removes elements from the array.

persons.splice(1,2); //It will remove 2nd and 3rd element

You can also have an array of objects or an array inside another array

, <span>Javascript – Arrays</span>, KandZ
it will print 8
, <span>Javascript – Arrays</span>, KandZ
it will print 3

strings are also arrays but you cannot use all the methods that an array or an object has. Those are push(), pop() and splice(). Instead strings have concat(), substring() and replace().

            var str = "Kronos";
            var str2 = str.concat("Zeus");
            console.log(str2);
            str2 = str2.replace("Kro","Bra")
            console.log(str2);
            str2 = str2.substring(6, str2.length);
            console.log(str2);
, <span>Javascript – Arrays</span>, KandZ

You can also iterate an array. There are two ways: The first one is by using the foreach() method that takes a single argument. This argument is a callback function and takes up to 3 parameters:

  1. the current element
  2. the index of the current element
  3. the array itself
, <span>Javascript – Arrays</span>, KandZ

, <span>Javascript – Arrays</span>, KandZ

The second way is by using the loop statements:

, <span>Javascript – Arrays</span>, KandZ
103230cookie-checkJavascript – ArraysJavascript – Arrays

Related posts

One Thought to “Javascript – Arrays

Comments are closed.