array in javascript

Declaration

To declare an array in Javascript, you can use the following syntax:

index.tsx
let arrayName = []; // empty array

let arrayName = [value1, value2, ...]; // array with initial values
104 chars
4 lines

Example:

index.tsx
let myArray = [];
let myOtherArray = [1, 2, 3];
48 chars
3 lines

Manipulation

To modify an existing array or add elements to it, you can use the following methods:

index.tsx
myArray.push(value); // add an element to the end of the array

myArray.pop(); // remove the last element of the array

myArray.unshift(value); // add an element to the beginning of the array

myArray.shift(); // remove the first element of the array

myArray.splice(index, howMany, item1, ..., itemN); // remove or replace elements from the array
348 chars
10 lines

Example:

index.tsx
let myArray = [1, 2, 3];
myArray.push(4); // myArray is now [1, 2, 3, 4]
myArray.pop(); // myArray is now [1, 2, 3]
myArray.unshift(0); // myArray is now [0, 1, 2, 3]
myArray.shift(); // myArray is now [1, 2, 3]
myArray.splice(1, 1, 4); // myArray is now [1, 4, 3]
265 chars
7 lines

Iteration

To loop through the elements of an array, you can use the following methods:

index.tsx
for (let i = 0; i < myArray.length; i++) {
  console.log(myArray[i]);
}

myArray.forEach(function(element) {
  console.log(element);
});

myArray.map(function(element) {
  return element + 1;
});
196 chars
12 lines

Example:

index.tsx
let myArray = [1, 2, 3];

for (let i = 0; i < myArray.length; i++) {
  console.log(myArray[i]); // output: 1, 2, 3
}

myArray.forEach(function(element) {
  console.log(element); // output: 1, 2, 3
});

let newArray = myArray.map(function(element) {
  return element + 1;
});

console.log(newArray); // output: [2, 3, 4]
320 chars
16 lines

gistlibby LogSnag