JS Array

Arrays in JavaScript

In JavaScript, an array is a special type of variable that can hold multiple values at once. Think of it like a list or a container that can store several items (such as numbers, strings, or even other arrays) in a single variable. These items are ordered and can be accessed using an index (which starts from 0).

Array-in-js

Array Declaration in JavaScript

You can declare arrays in JavaScript using the following syntax:

let array1 = []; // Declares an empty array
let array2 = [1, 2, 3]; // Declares an array with elements 1, 2, and 3
let array3 = [“apple”, “banana”, “cherry”]; // Declares an array of strings

Array with a defined set of elements:

let array1 = [4, 5, 1, 7, 3]; // array1 has 5 elements

Understanding the Array Declaration

•  let array1 = [4, 5, 1, 7, 3];
This declares an array array1 with 5 specific elements: 4, 5, 1, 7, 3.
  let array2 = new Array(5);
This creates an empty array array2 with 5 empty slots. The values will be undefined initially.
 let array3 = [“apple”, “banana”, “cherry”];
This declares an array array3 with 3 string elements: “apple”, “banana”, and “cherry”.

Example: Creating and Accessing an Array

Let’s create a simple array with values and demonstrate how to access a specific element by its index.

Scenario: Create an array with values [2, 4, 10, 5, 15, 3] and print the 3rd element (index 2).

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Arrays</title>
</head>
<body>
<script>
let numbers = [2, 4, 10, 5, 15, 3]; // Creating an array with values
console.log(“The third element: ” + numbers[2]); // Accessing the 3rd element (index 2)
</script>
</body>

Output
Accessing-in-array

Code Explanation:

 let numbers = [2, 4, 10, 5, 15, 3];
This line creates an array numbers with 6 elements: 2, 4, 10, 5, 15, 3.
•  console.log(“The third element: ” + numbers[2]);
Here, we are accessing the third element of the array by using index 2 (because array indexing starts from 0). So numbers[2] returns 10.
•  Output
The third element :10,which is displayed in the console

Array Methods in JavaScript

JavaScript arrays come with a variety of built-in methods that allow you to modify or interact with the elements inside an array. Let’s look at some of the most commonly used methods:

Methods Description Example
push() Adds one or more elements to the end of an array and returns the new length of the array. let fruits = [“apple”, “banana”]; fruits.push(“cherry”); // Adds ‘cherry’ to the end console.log(fruits); // Output: [“apple”, “banana”, “cherry”]
pop() Removes the last element from an array and returns it. let fruits = [“apple”, “banana”, “cherry”]; let lastFruit = fruits.pop(); // Removes ‘cherry’ console.log(lastFruit); // Output: ‘cherry’ console.log(fruits); // Output: [“apple”, “banana”]
shift() Removes the first element from an array and returns it, shifting all remaining elements down. let fruits = [“apple”, “banana”, “cherry”]; let firstFruit = fruits.shift(); // Removes ‘apple’ console.log(firstFruit); // Output: ‘apple’ console.log(fruits); // Output: [“banana”, “cherry”]
unshift() Adds one or more elements to the beginning of an array and returns the new length of the array. let fruits = [“banana”, “cherry”]; fruits.unshift(“apple”); // Adds ‘apple’ to the beginning console.log(fruits); // Output: [“apple”, “banana”, “cherry”]
splice() Changes the contents of an array by removing or replacing existing elements and/or adding new ones. let fruits = [“apple”, “banana”, “cherry”]; fruits.splice(1, 1, “orange”, “grapes”); // Removes 1 element at index 1 and adds “orange” and “grapes” console.log(fruits); // Output: [“apple”, “orange”, “grapes”, “cherry”]
slice() Combines two or more arrays into a new array. let fruits1 = [“apple”, “banana”]; let fruits2 = [“cherry”, “date”]; let allFruits = fruits1.concat(fruits2); // Merges both arrays console.log(allFruits); // Output: [“apple”, “banana”, “cherry”, “date”]
forEach() Executes a provided function once for each array element. let fruits = [“apple”, “banana”, “cherry”]; fruits.forEach(function(fruit) { console.log(fruit); // Logs each fruit individually }); // Output: // apple // banana // cherry
map() Creates a new array populated with the results of calling a provided function on every element in the array. let numbers = [1, 2, 3]; let squared = numbers.map(function(num) { return num * num; }); console.log(squared); // Output: [1, 4, 9]
filter() Creates a new array with all elements that pass the test implemented by the provided function. let numbers = [1, 2, 3, 4, 5]; let evenNumbers = numbers.filter(function(num) { return num % 2 === 0; }); console.log(evenNumbers); // Output: [2, 4]

Iterating Over Arrays in JavaScript

You can use different techniques to loop through arrays in JavaScript. Here are a few common ones:

1. Using a for loop:

Using-over-Arrays

<body>
<script>
let fruits = [“apple”, “banana”, “cherry”];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]); // Logs each element
}
</script>
</body>

Code Explanation:

1. Initialization: let i = 0 – Start with the first element of the array (i = 0).
2. Condition: i < fruits.length – Continue looping as long as i is less than the length of the array (so that every element gets accessed).
3. Increment: i++ – After each iteration, increment i by 1 (moving to the next index).
4. Inside the loop: console.log(fruits[i]) – The console.log prints the element at index i for each iteration.

Output

2. Using for...of loop:

Using-for-of-loop

<body>
<script>
let fruits = [“apple”, “banana”, “cherry”];
for (let fruit of fruits) {
console.log(fruit); // Logs each element
}
</script>
</body>

Code Explanation:

1. The forEach() method takes a callback function as an argument. This callback is executed once for each element in the fruits array.
2. In this case, the callback function logs each fruit (the current element in the array) to the console.

Output
Using-for-each

Course Video

Practice Scenarios

1. Create a JavaScript program that enables users to interact with an array. The program allows users to input values and choose whether to insert these values at the beginning or the end of the array.

dropdown value: “Insert First” & “Insert Last”
Additionally, Once a value is added, create a function to display the entire array as a string on the document.

The task is to create a JavaScript program that enables users to interact with an array. Users can input values and choose whether to insert these values at the beginning or the end of the array. Additionally, there should be a function to display the entire array as a string on the document.
1. Create Input Fields and Dropdown: Use HTML elements (<input>, <select>, <option>) to create input fields and a dropdown for user interaction.
2. Create Array and Functions: Use JavaScript to create an array, add values based on user input and choice, and display the array.

Here’s an example program:

<body>
<h2>Array Manipulation</h2>
<label for=”valueInput”>Enter Value:</label>
<input type=”text” id=”valueInput”>
<label for=”insertOption”>Choose Insertion:</label>
<select id=”insertOption”>
<option value=”insertFirst”>Insert First</option>
<option value=”insertLast”>Insert Last</option>
</select>
<button onclick=”insertValue()”>Insert Value</button>
<h3>Array:</h3>
<div id=”arrayOutput”></div>
<script>
var myArray = [];
function insertValue() {
// Get user input and insertion option
var value = document.getElementById(“valueInput”).value;
var insertOption = document.getElementById(“insertOption”).value;
// Insert value based on user choice
if (insertOption === “insertFirst”) {
myArray.unshift(value); // Insert at the beginning
} else if (insertOption === “insertLast”) {
myArray.push(value); // Insert at the end
}

Output

Normal Insert Value

Array-Manipulation

Selected First Insert Value

Array-manipulation-

Selected Last Insert Value

Array-manipulation-z
2. Create a JavaScript program that allows users to enter a value and click a button to check if the value exists in the array. If the value exists, the program should print the entire array to the console. If the value doesn’t exist, it should print “false” to the console.

The task is to create a JavaScript program that allows users to enter a value and check if the value exists in the array. If the value exists, the program should print the entire array to the console; otherwise, it should print “false.” Here’s a simple explanation:
1. Create Input Field and Button: Use HTML elements (<input>, <button>) to create an input field and a button for user interaction.
2. Create Array and Functions: Use JavaScript to create an array, check if the entered value exists, and print the array or “false” to the console.

Here’s an example program:

<body>
<h2>Array Value Checker</h2>
<label for=”valueInput”>Enter Value:</label>
<input type=”text” id=”valueInput”>
<button onclick=”checkValue()”>Check Value</button>
<script>
var myArray = [10, 20, 30, 40, 50]; // Initial array
function checkValue() {
// Get user input
var value = document.getElementById(“valueInput”).value;
// Check if the value exists in the array
var exists = myArray.includes(parseInt(value));
// Print the array or “false” to the console
if (exists) {
console.log(“Array: ” + myArray.join(‘, ‘));
} else {
console.log(false);
}

Output

If the value exists

Array-value-checker

If the value exists

Array-value-checker-
3. Create a JavaScript program that implements a simple To-Do List program in JavaScript where users can input tasks using an input element, and the tasks are added to a list.

The task is to create a JavaScript program that implements a simple To-Do List. Users can input tasks using an input element, and the tasks are added to a list. Here’s a simple explanation:
1. Create Input Field, Button, and Task List: Use HTML elements (<input>, <button>, <ul>, <li>) to create an input field, a button, and a list for tasks.
2. Create Functions to Add Tasks: Use JavaScript to create functions that add tasks to the list when the button is clicked.

Here’s an example program:

<body>
<h2>To-Do List</h2>
<label for=”taskInput”>Add Task:</label>
<input type=”text” id=”taskInput”>
<button onclick=”addTask()”>Add Task</button>
<ul id=”taskList”></ul>
<script>
function addTask() {
// Get user input
var taskInput = document.getElementById(“taskInput”);
var taskText = taskInput.value;
// Check if the input is not empty
if (taskText.trim() !== “”) {
// Create a new list item
var newTask = document.createElement(“li”);
newTask.textContent = taskText;

Output

js-to-do-list
4. Display the array on the document and create a dynamic list using the same array, using a loop or a built-in method.

const fruits = [“apple”“, “banana”“, “cherry”“, “date”“, “fig”];
HTML Code:
<button id=“createDynamicList”>Create List Array</button>
<ul id=“list”></ul>
Note: Use an external JS file and show the HTML file first with your name before recording the completed program.”

The task is to create a simple web page that displays an array of fruits and provides a button. When the user clicks the button, it should create a list on the web page with the fruits from the array.
1. Array Display: Show the array of fruits on the webpage when it loads.
2. Button: Provide a button with the text “Create List Array.”
3. Dynamic List: When the user clicks the button, use JavaScript to create a dynamic list (unordered list – <ul>) on the webpage using the fruits from the array.
4. External JavaScript File: Use an external JavaScript file named script.js to write the JavaScript code

Here’s an example program:

HTML File (index.html):

<!DOCTYPE html>
<html lang=”en”>
<head>

JavaScript File (script.js):

document.addEventListener(“DOMContentLoaded”, function() {
const fruits = [“apple”, “banana”, “cherry”, “date”, “fig”];
// Display the array on the document
document.getElementById(“arrayDisplay”).textContent = “Array: ” + fruits.join(‘, ‘);
// Create dynamic list on button click
document.getElementById(“createDynamicList”).addEventListener(“click”, function() {
createDynamicList(fruits);
});
// Function to create dynamic list
function createDynamicList(array) {
var listContainer = document.getElementById(“list”);
// Clear existing list
listContainer.innerHTML = “”;
// Create list items using a loop
for (var i = 0; i < array.length; i++) {
var listItem = document.createElement(“li”);
listItem.textContent = array[i];
listContainer.appendChild(listItem);
}
}
});

Output

Before Click

Array-Display

After Click

Array-Display-and-Dynamic-list
5. Develop a program that utilizes custom events. Create an event listener that responds to a custom event and updates the content on the webpage accordingly.

The task is to create a simple JavaScript to-do list program.
Imagine you have a web page with an input field to add tasks, a button to add tasks, another input field to search for tasks, and a button to search for tasks.
1. Adding Tasks:
– User types “Buy groceries” and clicks the “Add Task” button.
– The to-do list now shows: “Buy groceries.”
– The user types “Complete homework” and clicks the “Add Task” button.
– The to-do list now shows:
– “Buy groceries.”
– “Complete homework.”
2. Searching for Tasks:
-The user types “groceries” in the search field and clicks the “Search” button.
– The program shows: “Buy groceries.”
– User types “work” in the search field and clicks the “Search” button.
– The program shows: “Complete homework.”

Here’s an example program:

<body>
<input type=“text” id=“taskInput” placeholder=“Add Task”>
<button onclick=“addTask()”>Add Task</button>
<input type=“text” id=“searchInput” placeholder=“Search Task”>
<button onclick=“searchTasks()”>Search</button>
<ul id=“taskList”></ul>
<script>
var tasks = [];
function addTask() {
var taskInput = document.getElementById(“taskInput”).value;
tasks.push(taskInput);
displayTasks();
}
function searchTasks() {
var searchInput = document.getElementById(“searchInput”).value.toLowerCase();
var filteredTasks = tasks.filter(task => task.toLowerCase().includes(searchInput));
displayTasks(filteredTasks);
}
function displayTasks(taskArray = tasks) {
var taskList = document.getElementById(“taskList”);
taskList.innerHTML = “; // Clear existing list
taskArray.forEach(task => {
var listItem = document.createElement(“li”);
listItem.textContent = task;
taskList.appendChild(listItem);
});
}

</script>
</body>

Output

Adding Tasks

js-add-task

Searching Task

Js-Searching-task
Frequently Asked Questions

Still have a question?

Let's talk

An array is a special variable that can hold multiple values in a single variable, stored as elements in a specific order. Learn more in our JavaScript array free course video.

Example:

let fruits = [“Apple”, “Banana”, “Cherry”]; 

let numbers = new Array(1, 2, 3); 

Explore this further in our JS array with free video tutorial.

Access elements using their index. The index starts at 0.
Example:

 

let fruits = [“Apple”, “Banana”]; 

console.log(fruits[0]); // Output: “Apple” 

Check out practical examples in the Free JavaScript array tutorial for beginners.

  • Add: Use push() to add to the end and unshift() to add to the beginning.
  • Remove: Use pop() to remove from the end and shift() to remove from the beginning.
    Example:

let numbers = [1, 2, 3]; 

numbers.push(4); // [1, 2, 3, 4] 

numbers.pop(); // [1, 2, 3] 

Learn this technique in our JS array explained with free course video.

You can use loops like for, for…of, or array methods like forEach().
Example:

let fruits = [“Apple”, “Banana”]; 

fruits.forEach(fruit => console.log(fruit)); 

Watch these methods in action in our JavaScript array free course video.

Common methods include:

  • map(): Transforms each element.
  • filter(): Filters elements based on a condition.
  • reduce(): Reduces an array to a single value.
  • sort(): Sorts the array.
  • splice(): Adds/removes elements at specific indexes.
    Find these explained in our JS array with free video tutorial.

Yes, JavaScript arrays can store elements of different data types.
Example:

let mixedArray = [42, “Hello”, true, { key: “value” }]; 

Learn more in the Free JavaScript array tutorial for beginners.

  1. How do I check the length of an array?
    Use the .length property to find the number of elements in an array.
    Example:

 

let numbers = [1, 2, 3]; 

console.log(numbers.length); // Output: 3 

Explore this in the JS array explained with free course video.

Use the .length property to find the number of elements in an array.
Example:

let numbers = [1, 2, 3]; 

console.log(numbers.length); // Output: 3 

Explore this in the JS array explained with free course video.

  • map() returns a new array with transformed elements.
  • forEach() executes a function for each element but doesn’t return a new array.
    Discover their differences in the JavaScript array free course video.

Use the concat() method or the spread operator (…).
Example:

let arr1 = [1, 2]; 

let arr2 = [3, 4]; 

let merged = […arr1, …arr2]; // [1, 2, 3, 4] 

Learn this in the JS array with free video tutorial.