JS is Array
JS is an object-oriented programming language commonly used for web development. It provides a built-in array data type that allows us to store and manipulate multiple values in a single variable.
In JavaScript, an array is defined using square brackets ([]), and the values inside the array are separated by commas. Here is an example of how to declare an array and assign values to it:
javascript
const fruits = ['apple', 'banana', 'orange'];
We can access individual elements in an array using their index. The index of the first element is 0, the second element is 1, and so on. Here is an example:
javascript
console.log(fruits[0]); // Output: 'apple'
console.log(fruits[2]); // Output: 'orange'
We can also modify the elements in an array by assigning a new value to a specific index:
javascript
fruits[1] = 'grape';
console.log(fruits); // Output: ['apple', 'grape', 'orange']
The length property of an array returns the number of elements present in the array:
javascript
console.log(fruits.length); // Output: 3
We can use various built-in methods to manipulate arrays, such as push(), pop(), shift(), unshift(), splice(), and concat(). Here are some examples:
javascript
fruits.push('mango'); // adds 'mango' to the end of the array
console.log(fruits); // Output: ['apple', 'grape', 'orange', 'mango']
fruits.pop(); // removes the last element from the array
console.log(fruits); // Output: ['apple', 'grape', 'orange']
fruits.shift(); // removes the first element from the array
console.log(fruits); // Output: ['grape', 'orange']
fruits.unshift('kiwi'); // adds 'kiwi' to the front of the array
console.log(fruits); // Output: ['kiwi', 'grape', 'orange']
fruits.splice(1, 1); // removes one element at index 1
console.log(fruits); // Output: ['kiwi', 'orange']
const newFruits = fruits.concat(['pear', 'melon']); // concatenates two arrays
console.log(newFruits); // Output: ['kiwi', 'orange', 'pear', 'melon']
In conclusion, JavaScript provides a versatile array data type that enables us to store and manipulate multiple values. It comes with various methods to add, remove, and modify elements in an array, making it a powerful tool for managing collections of data.