JS Array Const 🎯

beginner
18 min

JS Array Const 🎯

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!

What is an Array Const? 💡

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:

javascript
// 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.

Accessing Array Elements 💡

To access an element in an array const, simply reference its index number inside square brackets. Here's an example:

javascript
// Accessing the first element console.log(fruits[0]); // Output: "apple"

Changing Array Elements 💡

Unlike immutable values, array elements can be changed. Here's an example:

javascript
// 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".

Adding Elements to an Array Const 💡

To add an element to an array const, you can use the push() method. Here's an example:

javascript
// 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.

Removing Elements from an Array Const 💡

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:

javascript
// 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.

Multi-dimensional Array Consts 💡

A multi-dimensional array const is an array containing other arrays. Here's an example:

javascript
// 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.

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

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! 📝