Q:

what is an array in javascript

//Creating a list
var fruits = ["Apple", "Banana", "Cherry"];

//Creating an empty list
var books = [];

//Getting element of list
//Lists are ordered using indexes
//The first element in an list has an index of 0, 
//the second an index of 1,
//the third an index of 2,
//and so on.
console.log(fruits[0]) //This prints the first element 
//in the list fruits, which in this case is "Apple"

//Adding to lists
fruits.push("Orange") //This will add orange to the end of the list "fruits"
fruits[1]="Blueberry" //The second element will be changed to Blueberry

//Removing from lists
fruits.splice(0, 1) //This will remove the first element,
//in this case Apple, from the list
fruits.splice(0, 2) //Will remove first and second element
//Splice goes from index of first argument to index of second argument (excluding second argument)
11
// Initializing while declaring 
// Creates an array having elements 10, 20, 30, 40, 50 
var house = new Array(10, 20, 30, 40, 50); 
  
//Creates an array of 5 undefined elements 
var house1 = new Array(5); 
  
//Creates an array with element 1BHK 
var home = new Array("!BHK"); 
5
// Javasscripts Arrays are not fixed length
var person = [];
person[0] = "John";
person[1] = "Doe";
person[2] = 46;

var x = person.length;     // person.length will return 3
var y = person[0];         // person[0] will return "John"
3
//one line

var cars = ["Toyota", "Jeep", "BMW"];

//multiple lines

var cars = [
 "Toyota",
 "Jeep",
 "BMW"
];
15
var widgetTemplats = [
    {
        name: 'compass',
        LocX: 35,
        LocY: 312
    },
    {
        name: 'another',
        LocX: 52,
        LocY: 32
    }
]
5

var cars = [

  "Saab",

    "Volvo",

    "BMW"

]; 
4
//create array
var things = ["banana", "car", "computer"];
//access array(starts at 0)
things[0]
//iterate through an array
for (var i = 0; i < things.length; i++) {
  things[i]
}
3
// an Array is like a list
var food['Pickles', 'Bread' , 'Mango']
1

New to Communities?

Join the community