Arrays

Arrays are ordered sequences of values. Those values can be of any data type and are separated by comma. Arrays have to be declared inside braces.

var students = [ "John" , "Mary", "Paul" ];
    var primeNumbers = [ 2, 3, 5, 7, 11, 13 ];

Like strings, arrays also have length and their elements have their own indexes.

students = [ "John" , "Mary", "Paul" ];
    console.log(students.length); // The console will show 3
    console.log(students[0]);  // The console will show "John"

Array elements can also be arrays and objects.

var groups = [ 
        [ "John" , "Mary" ],
        [ "Peter" , "Joana", "Andrew", "Julio" ],
        [ "Caroline" , "Helen", "Mark" ]
    ];
console.log(groups.length); // The console will 3
    console.log(groups[1]);  // The console will [ "Peter" , "Joana", "Andrew", "Julio" ]

    /* We can access arrays inside arrays by adding the index notation as many times as needed */

    console.log(grupos[1][2]);  // The console will "Andrew"

Array operations

var courses = [ "HTML", "Python", "PHP" ];

    courses.push("Javascript");

    console.log(courses);  // The console will show [ "HTML", "Python", "PHP", "Javascript" ]

    courses.unshift("Bootstrap");

    console.log(courses);  // The console will show [ "Bootstrap", "HTML", "Python", "PHP", "Javascript" ]

    courses.pop();

    console.log(courses);  // The console will show [ "Bootstrap", "HTML", "Python", "PHP" ]

    courses.shift();

    console.log(courses);  // The console will show [ "HTML", "Python", "PHP" ]

It's also possible to redefine elements using the index notation

var ingredients = [ "bread", "cheese", "ham" ];

    ingredients[0] = "whole bread";

    console.log(ingredients);  // The console will show [ "whole bread", "cheese", "ham" ]

The slice method extracts part of an array. We do it by choosing a start and an end index (end element not included).

var students = [ "Peter" , "Joana", "Andrew", "Julio", "Kate", "Marie" ];
    console.log( students.slice(0,3) );
//"Peter" 0, "Joana"1, "Andrew"2, "Julio"3, "Kate"4, "Marie"5
    // The console will show [ "Peter" , "Joana", "Andrew" ]

By omitting省略 second value we go until the last element with it included.

var students = [ "Peter" , "Joana", "Andrew", "Julio", "Kate", "Marie" ];
    
    console.log( students.slice(3,) );
    // The console will show ["Julio", "Kate", "Marie"]