Skip to content

Instantly share code, notes, and snippets.

@iJKTen
Last active May 31, 2020 22:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save iJKTen/5c67d005ec7c7b9604897d5b517f0ccd to your computer and use it in GitHub Desktop.
Save iJKTen/5c67d005ec7c7b9604897d5b517f0ccd to your computer and use it in GitHub Desktop.
Array Basics
// Declare an array
const arr = [10, 20, 4, 50];
// Output the array
console.log({arr});
// Get the element at the first position
// You index into the array with the help of square brackets.
const firstElement = arr[0]
//Output the value
console.log({firstElement});
// Get the element at the first position
const lastElement = arr[arr.length - 1];
//Output the value
console.log({lastElement});
// Loop over an array using a for loop
for(let index = 0; index < arr.length; index++) {
console.log('using for loop', {index: index, value: arr[index]});
}
// Loop over an array using forEach
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
arr.forEach(function(element, index) {
console.log('using forEach', {index: index, value: element});
});
// Add an element at the end of the array
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
arr.push(80);
// Output the array after adding a new element
console.log('element added at the end of the array', {arr});
// Add an element at the start of the array
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift
arr.unshift(90);
// Output the array after adding a new element
console.log('element added at the start of the array', {arr});
// Remove an element from the end of the array
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
const elementRemoved = arr.pop();
// Output the array after removing an element from the end
console.log('element removed at the end of the array', {element: elementRemoved, arr: arr});
// Remove an element from the start of the array
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift
const elementRemoved2 = arr.shift();
// Output the array after removing an element from the start
console.log('element removed at the end of the array', {element: elementRemoved2, arr: arr});
// Get an element at index 1, meaning the second element
console.log('element at index 1', arr[1]);
// Update an element at index 1, meaning the second element
arr[1] = 33
console.log('element at index 1 after update', arr[1]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment