8.1 Creating Arrays
Arrays in JavaScript are a data structure that lets you store ordered collections of values. These values can be of any type, including numbers, strings, objects, and even other arrays. Arrays in JavaScript are dynamic, meaning their size can change during the execution of a program.
Creating and Initializing Arrays:
1. Using an Array Literal
The simplest way to create an array is using square brackets []:
let array1 = []; // empty array
let array2 = [1, 2, 3]; // array with three elements
2. Using the Array Constructor
The Array constructor allows you to create arrays using a function:
let array1 = new Array(); // empty array
let array2 = new Array(3); // array with length 3 (all elements undefined)
let array3 = new Array(1, 2, 3); // array with three elements
3. Filling an Array with Values
You can fill an array with values after its creation:
let array = [];
array[0] = 'apple';
array[1] = 'banana';
array[2] = 'cherry';
8.2 Accessing Array Elements
Array elements are indexed starting from zero. Access elements using square brackets:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits[0]); // "Apple"
console.log(fruits[1]); // "Banana"
console.log(fruits[2]); // "Cherry"
Modifying Array Elements
Array elements can be changed using their indices:
let fruits = ["Apple", "Banana", "Cherry"];
fruits[1] = "Blueberry";
console.log(fruits); // ["Apple", "Blueberry", "Cherry"]
Property length
The length property returns the number of elements in an array:
let fruits = ["Apple", "Banana", "Cherry"];
console.log(fruits.length); // 3
8.3 Array Methods for Adding and Removing Elements
1. Method push
The push() method adds one or more elements to the end of an array and returns the new length of the array:
let fruits = ['apple', 'banana'];
fruits.push('cherry'); // ['apple', 'banana', 'cherry']
console.log(fruits.length); // 3
2. Method pop
The pop() method removes the last element from an array and returns it:
let fruits = ['apple', 'banana', 'cherry'];
let last = fruits.pop(); // 'cherry'
console.log(fruits); // ['apple', 'banana']
3. Method shift
The shift() method removes the first element from an array and returns it. All other elements shift to the left by one:
let fruits = ['apple', 'banana', 'cherry'];
let first = fruits.shift(); // 'apple'
console.log(fruits); // ['banana', 'cherry']
4. Method unshift
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array:
let fruits = ['banana', 'cherry'];
fruits.unshift('apple'); // ['apple', 'banana', 'cherry']
console.log(fruits.length); // 3
GO TO FULL VERSION