Welcome to our deep dive into JavaScript Array Const! 📝
In this lesson, we'll explore the ins and outs of working with constant arrays in JavaScript, a fundamental concept for any JavaScript developer. Let's get started!
An array const is a collection of values, all of the same data type, stored in one variable. Unlike regular variables, arrays can hold multiple values and access them by their index number.
Here's an example of an array const:
// Creating an array const
const fruits = ["apple", "banana", "cherry"];In this example, we've created an array called fruits with three elements: "apple", "banana", and "cherry". Each element is stored at a specific index, starting from 0 for the first element.
To access an element in an array const, simply reference its index number inside square brackets. Here's an example:
// Accessing the first element
console.log(fruits[0]); // Output: "apple"Unlike immutable values, array elements can be changed. Here's an example:
// Changing the second element
fruits[1] = "grape";
console.log(fruits); // Output: ["apple", "grape", "cherry"]In this example, we've changed the second element of the fruits array to "grape".
To add an element to an array const, you can use the push() method. Here's an example:
// Adding an element to the end of the array
fruits.push("orange");
console.log(fruits); // Output: ["apple", "grape", "cherry", "orange"]In this example, we've added "orange" to the end of the fruits array using the push() method.
To remove an element from an array const, you can use the pop() method to remove the last element or the splice() method to remove an element at a specific index. Here's an example:
// Removing the last element
fruits.pop();
console.log(fruits); // Output: ["apple", "grape", "cherry"]
// Removing the second element
fruits.splice(1, 1);
console.log(fruits); // Output: ["apple", "cherry"]In this example, we've removed the last element using the pop() method and the second element using the splice() method.
A multi-dimensional array const is an array containing other arrays. Here's an example:
// Creating a multi-dimensional array const
const matrices = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];In this example, we've created a multi-dimensional array called matrices with three elements, each being an array of integers.
What data type is an array const?
We hope this lesson has been helpful in understanding JavaScript Array Consts! Remember to practice regularly, and soon you'll be a JavaScript pro! 📝