Welcome to our tutorial on Arrays in JavaScript!
In this tutorial, we're going to explore how to store a list of colors in an array. Are you ready to get started?
Step 1: Create an Array
Open your index.js
file and let's create an array to store our list of colors. An array is a collection of values of the same type stored in a single variable. We can create an array using square brackets []
.
Write the following code in your index.js
file:
let colors = []
What's happening here?
We're declaring a variable colors
and initializing it with an empty array []
. This array can hold multiple values, and we'll add some colors to it soon!
Step 2: Add Colors to the Array
Let's add some colors to our array. We can do this using the push()
method, which adds a new element to the end of the array.
Add the following code to your index.js
file:
colors.push("Red");colors.push("Blue");colors.push("Green");colors.push("Yellow");
What's happening here?
We're using the push()
method to add four colors to our colors
array: "Red", "Blue", "Green", and "Yellow".
Step 3: Log the Array
Let's log our colors
array to the console to see what it looks like. Add the following code to your index.js
file:
console.log(colors)
What's happening here?
We're using the console.log()
function to print our colors
array to the console.
Run the Code!
Click the "Run" button to execute your code. You should see the following output in your console:
[ 'Red', 'Blue', 'Green', 'Yellow' ]
Congratulations! You've successfully created an array and added colors to it!
Real-World Example
Imagine you're a web developer building a color palette generator for a design website. You need to store a list of colors that users can select from. Using an array, you can store a list of colors and then use them to generate a color palette.
What's Next?
Now that you've learned about arrays, you're ready to move on to the next concept: Objects! In our next tutorial, we'll explore how to create objects and use them to store more complex data.
Keep practicing, and you'll become a JavaScript master in no time!
Code so far:
let colors = []colors.push("Red")colors.push("Blue")colors.push("Green")colors.push("Yellow")console.log(colors)
What's your next step?
Click the "Run" button to execute your code, and then move on to the next tutorial to learn about Objects!
Tests