Everything you need to know about JavaScript Array
Samiul Islam
Posted on September 16, 2021
In this article, I will discuss everything you need to know about Array in JavaScript. So, Let’s get started 😐
1. Create an Array
// Create an array
const colors = ['black', 'white', 'green', 'blue'];
2. Getting length of an Array
// Getting length of an Array
const arrLength = colors.length;
console.log('The length of the array is = ', arrLength);
// Expected output: The length of the array is = 4
3. Getting element by index position
// Getting element by index position
const getValueByIndex = colors[0];
console.log('Index of first element is = ', getValueByIndex);
//Expected output: Index of first element is = black
4. Array indexOf() method => Used to get index of any single element
// Array indexOf() method => Used to get index of any single element
const getIndexByValue = colors.indexOf('white');
console.log('The index of the element is = ', getIndexByValue);
// Expected output: The index of the element is = 1
5. Array push() method => Used to add element at end of an Array
// Array push() method => Used to add element at end of an Array
console.log('Previous array', colors);
colors.push('Orange'); // Added 13 at the end of previous array colors
console.log('Array after pushing a value ', colors);
/* Expected Output:
Previous array [ 'black', 'white', 'green', 'blue' ]
Array after pushing a element [ 'black', 'white', 'green', 'blue', 'Orange' ] */
6. Array pop() method => Used to remove last element from an Array
// Array pop() method => Used to remove last element from an Array
console.log('Array before pop', colors);
colors.pop(); // Removed last element of the array colors
console.log('Array after pop', colors);
/*Expected OutPut:
Array before pop [ 'black', 'white', 'green', 'blue', 'Orange' ]
Array after pop [ 'black', 'white', 'green', 'blue' ] */
7. Array includes() method => Used to check whether an array includes a certain element inside its entries, and return true or false.
// Array includes() method => Used to check whether an array includes a certain element inside its entries, and return true or false.
const isSkyBlueAdded = colors.includes('sky-blue');
console.log(isSkyBlueAdded);
// Expected Output: false
Thanks for your patience 😎
Get connected with me:
LinkedIn: https://www.linkedin.com/in/softsamiul
GitHub: https://github.com/softsamiul
💖 💪 🙅 🚩
Samiul Islam
Posted on September 16, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.