An array is a data structure that stores a collection of elements. These elements can be of any data type, including numbers, strings, objects, or even other arrays.
Arrays in JavaScript are zero-indexed, meaning the first element is accessed with an index of 0, the second with an index of 1, and so on.
To create an array, we can use the array literal syntax, which involves enclosing the elements inside square brackets [].
// Declaring an empty array
let myArray = [];
// defining an array with elements
let skills = ['javascript', 'php', 'dotnet'];
// defining an array with elements
let skills = ['javascript', 'php', 'dotnet'];
Arrays in JavaScript can hold multiple data types making it complex data structure.
// Arrays can contain elements of different types
let mixedArr = [23, 'coders', true, { name: 'Rohit' }];
// Accessing elements in an array
console.log(skills[0]); // Outputs: javascript
console.log(mixedArr[2]); // Outputs: true
// Modifying elements in an array
skills[1] = 'laravel'; // Modifying the second element
console.log(skills); // Outputs: ['javascript', 'laravel', 'dotnet'];
// Arrays have a length property
console.log(skills.length); // Outputs: 3
// Adding elements to an array
skills.push('python');
console.log(skills); // Outputs: ['javascript', 'laravel', 'dotnet', 'python'];
// Removing the last element from an array
let lastskill = skills.pop();
console.log(lastskill); // Outputs: python
console.log(skills); // Outputs: ['javascript', 'laravel', 'dotnet'];
// Iterating over elements in an array
skills.forEach(function(skill) {
console.log(skill);
});