Question based on arrays

๐ JavaScript Basics Arrays Questions for Beginners: Basics Explained
If you're learning JavaScript, understanding arrays is essential. Arrays allow you to store multiple values in a single variable โ making your code cleaner and more powerful. In this post, we'll cover the basics of arrays in JavaScript with simple examples.
๐น What is an Array?
An array is a collection of values stored in a single variable.
let fruits = ["apple", "banana", "mango"];
Here, fruits
is an array that holds 3 items (or elements).
๐น How to Create an Array
You can create arrays in a few ways:
let numbers = [1, 2, 3, 4]; // using square brackets
let emptyArray = []; // empty array
let mixed = [1, "hello", true]; // mixed data types
๐น Accessing Array Elements
Each element in an array has an index, starting from 0
.
let colors = ["red", "green", "blue"];
console.log(colors[0]); // red
console.log(colors[2]); // blue
๐น Changing Array Elements
You can change an element using its index:
colors[1] = "yellow";
console.log(colors); // ["red", "yellow", "blue"]
๐น Common Array Methods
1. push()
โ Adds an item to the end of the array
colors.push("purple");
2. pop()
โ Removes the last item
colors.pop();
3. unshift()
โ Adds an item to the beginning
colors.unshift("pink");
4. shift()
โ Removes the first item
colors.shift();
๐น Checking the Array Length
Use .length
to get the number of items in an array:
let numbers = [10, 20, 30];
console.log(numbers.length); // 3
๐น Looping Through an Array
You can loop through arrays with a for
loop:
for (let i = 0; i < numbers.length; i++) {
console.log(numbers[i]);
}
Or use .forEach()
for cleaner code:
numbers.forEach(function(num) {
console.log(num);
});
๐ Summary
โ
Arrays let you store multiple values
โ
You access elements using indexes (starting from 0)
โ
Arrays have many built-in methods like push()
, pop()
, length
, and forEach()
โ
Arrays can hold any type of data: numbers, strings, booleans, or even other arrays
Subscribe to my newsletter
Read articles from agastya shukla directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
