In JavaScript, arrays are utilized to hold several values within a single variable. Rather than having numerous distinct variables for every data item, you can consolidate everything into one array. This simplifies the process of managing lists of items such as numbers, names, or other information. In this post, we will examine how to create arrays, modify them, and delve into some useful methods that facilitate working with arrays.
An array is a structure that holds multiple values in one variable. It’s similar to a list capable of containing elements like numbers, strings, or other types of data. Each element has a position in the array known as an index, which begins at 0.
Syntax:
let arrayName = [item1, item2, item3, ...];
How to Create an Array?
In JavaScript, there are two primary approaches to creating arrays: utilizing array literals or the array constructor. Both methods enable the storage of multiple values but are written differently.
1. Using Array Literals
The most frequent and straightforward method to create an array is by employing array literals. An array literal consists of a list of values surrounded by square brackets [].
Example:
let course = ['HTML', 'CSS', 'JS'];
2. Using the Array Constructor
Another method to create an array is through the Array constructor. This requires invoking the Array() function. You can use this to initiate an empty array while also defining an array’s size.
Example (Empty Array):
let emptyArray = new Array();
Example (Array with a Size):
let numbers = new Array(3);
It will produce an array with 3 empty slots.
Example (Array with Values):
let course = new Array('HTML', 'CSS', 'JS');
Master the Latest Tools like React, Node.js, and More
JavaScript arrays are equipped with built-in functions that simplify manipulation and interaction with the data contained within them. Some frequently utilized array methods involve adding and removing elements, as well as traversing the array.
Adding Elements
There are several techniques for appending elements to an array in JavaScript. You can place elements at the start, end, or even at designated positions.
1. Adding to the End:
Using the push() method, you can append one or more elements to the conclusion of an array.
"+outputData+"");
jQuery(".maineditor30909 .code-editor-output").show();
jQuery("#runBtn30909 i.run-code").hide();
}
})
}
function hideOutput30909() {
var codeFragment = editor30909.getSession().getValue();
jQuery(".maineditor30909 .code-editor-output").hide();
}
// Bind event listeners to the buttons
document.getElementById("copyBtn30909").addEventListener("click", copyToClipboard30909);
document.getElementById("runBtn30909").addEventListener("click", executeCode30909);
document.getElementById("closeoutputBtn30909").addEventListener("click", hideOutput30909);
Result:
2. Inserting at the Beginning:
Utilizing the unshift() method, you are able to add one or more items at the start of an array.
Sample:
Javascript
Code Copied!
Result:
Removing Items
Eliminating elements from an array is equally straightforward as adding them. You can remove items from the front, back, or specific locations.
1. Deleting from the End:
The pop() method allows you to remove the final element from an array.
Sample:
Javascript
Code Copied!
Output:
2. Eliminating from the Beginning:
Utilizing the shift() function, you can eliminate the first item from an array.
Example:
Javascript
Code Copied!
Output:
Traversing Through Arrays
At times, you may need to access each element within an array and execute a certain operation on it. JavaScript offers a variety of methods for traversing arrays.
1. Utilizing a for loop:
With a for loop, you can traverse an array by index.
function closeOutput88739() {
jQuery(".maineditor88739 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn88739").addEventListener("click", copyCodeToClipboard88739);
document.getElementById("runBtn88739").addEventListener("click", runCode88739);
document.getElementById("closeoutputBtn88739").addEventListener("click", closeOutput88739);
Output:
2. Utilizing forEach():
The forEach() method represents a more contemporary approach to iterate through an array. It essentially executes a function on every element within the array.
Example:
Javascript
Code Copied!
var isMobile = window.innerWidth "");
editor96873.setValue(decodedContent); // Set the default text
editor96873.clearSelection();
editor96873.setOptions({
maxLines: Infinity
});
function decodeHTML96873(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard96873() {
const code = editor96873.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor96873 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor96873 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
function runCode96873() {
var code = editor96873.getSession().getValue();
function closeOutput96873() {
jQuery(".maineditor96873 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn96873").addEventListener("click", copyCodeToClipboard96873);
document.getElementById("runBtn96873").addEventListener("click", runCode96873);
document.getElementById("closeoutputBtn96873").addEventListener("click", closeOutput96873);
``````html
i.run-code").hide();
}
})
}
function closeoutput96873() {
var code = editor96873.getSession().getValue();
jQuery(".maineditor96873 .code-editor-output").hide();
}
// Link event listeners to the buttons
document.getElementById("copyBtn96873").addEventListener("click", copyCodeToClipboard96873);
document.getElementById("runBtn96873").addEventListener("click", runCode96873);
document.getElementById("closeoutputBtn96873").addEventListener("click", closeoutput96873);
Output:
Accessing and Altering Array Items
After you’ve established an array, you frequently need to access particular items or change the values contained in the array. JavaScript simplifies this process by enabling you to utilize indexes to retrieve and modify elements.
Indexing Arrays
Each item in an array is assigned a position, referred to as its index. The index is always a number, commencing at 0 for the initial item, 1 for the subsequent item, and so forth.
Example:
Javascript
Code Copied!
var isMobile = window.innerWidth ");
editor99773.setValue(decodedContent); // Set the default text
editor99773.clearSelection();
editor99773.setOptions({
maxLines: Infinity
});
function decodeHTML99773(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard99773() {
const code = editor99773.getValue(); // Retrieve code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code copied to clipboard!");
data: {
language: "js",
code: code,
cmd_line_args: "",
variablenames: "",
action:"compilerajax"
},
success: function(response) {
var myArray = response.split("~");
var data = myArray[1];
jQuery(".output99773").html("
"+data+"");
jQuery(".maineditor99773 .code-editor-output").show();
jQuery("#runBtn99773 i.run-code").hide();
}
})
}
function closeoutput99773() {
var code = editor99773.getSession().getValue();
jQuery(".maineditor99773 .code-editor-output").hide();
}
// Link event listeners to the buttons
document.getElementById("copyBtn99773").addEventListener("click", copyCodeToClipboard99773);
document.getElementById("runBtn99773").addEventListener("click", runCode99773);
document.getElementById("closeoutputBtn99773").addEventListener("click", closeoutput99773);
Output:
In this case,
course[0] retrieves the first element (HTML).
course[1] retrieves the second element (CSS), and so on.
If you attempt to access an index that does not exist, such as course[3], you will receive undefined.
Altering Elements
Within an array, you can alter its values simply by using the index of the item and assigning a new value.
Example:
Javascript
Code Copied!
Output:
In this instance,
The value at index 1 (‘CSS’) is altered to ‘Python’.
You can alter values at any index, and if the specified index is unavailable, JavaScript will generate blank slots (this is particularly true for higher indexes).
Example (Generating new index):
Javascript
Code Copied!
Output:
In this illustration,
JavaScript inserts CSS at index 5, leaving three unoccupied slots (indexes 2, 3, and 4) among the already existing elements.
``````html
Frequent Array Actions
Frequent array actions in JavaScript facilitate your interaction with collections of data. These actions encompass arranging (ordering elements), selecting (extracting particular elements), and transforming (converting elements into new representations).
1. Arranging Arrays
To arrange an array, you can utilize the sort() function.
Example:
Javascript
Code Copied!
Output:
2. Selecting Arrays
Utilizing the filter() function, you can generate a new array containing the elements that meet a test (a specified condition) provided by a callback function, without altering the original array.
Example:
Javascript
Code Copied!
var isMobile = window.innerWidth ");
editor13587.setValue(decodedContent); // Set the default text
editor13587.clearSelection();
editor13587.setOptions({
maxLines: Infinity
});
function decodeHTML13587(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to copy code to clipboard
function copyCodeToClipboard13587() {
const code = editor13587.getValue(); // Get code from the editor
navigator.clipboard.writeText(code).then(() => {
jQuery(".maineditor13587 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor13587 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error copying code: ", err);
});
}
``````html
});
}
function executeCode13587() {
var sourceCode = editor13587.getSession().getValue();
"+outputData+"");
jQuery(".maineditor13587 .code-editor-output").show();
jQuery("#runBtn13587 i.run-code").hide();
}
})
}
function hideOutput13587() {
var sourceCode = editor13587.getSession().getValue();
jQuery(".maineditor13587 .code-editor-output").hide();
}
// Add event listeners to the buttons
document.getElementById("copyBtn13587").addEventListener("click", copyToClipboard13587);
document.getElementById("runBtn13587").addEventListener("click", executeCode13587);
document.getElementById("closeoutputBtn13587").addEventListener("click", hideOutput13587);
Result:
3. Mapping Arrays
Using the map() function, you can modify every item in an array with a specific function, subsequently generating a new array consisting of the modified values.
Illustration:
Javascript
Code Copied!
Result:
Multi-Dimensional Arrays
A multi-dimensional array comprises arrays within arrays. This structure allows for the creation of arrays with multiple dimensions (such as a grid or matrix). A well-known instance is a 2D array, where each element within the primary array is also an array.
1. Constructing Multi-Dimensional Arrays
To establish a multi-dimensional array, arrays can be nested inside an overarching array. For instance, a 2D array can symbolize rows and columns.
function closeoutput27486() {
var code = editor27486.getSession().getValue();
jQuery(".maineditor27486 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn27486").addEventListener("click", copyCodeToClipboard27486);
document.getElementById("runBtn27486").addEventListener("click", runCode27486);
document.getElementById("closeoutputBtn27486").addEventListener("click", closeoutput27486);
Outcome:
2. Navigating Multi-Dimensional Arrays
To retrieve elements from a multi-dimensional array, you can utilize multiple indexes. The first index retrieves the outer array (the row), while the second index accesses the element within that row.
Illustration:
Javascript
Code Duplicated!
var isMobile = window.innerWidth ");
editor46329.setValue(decodedContent); // Assign the default text
editor46329.clearSelection();
editor46329.setOptions({
maxLines: Infinity
});
function decodeHTML46329(input) {
var doc = new DOMParser().parseFromString(input, "text/html");
return doc.documentElement.textContent;
}
// Function to duplicate code to clipboard
function copyCodeToClipboard46329() {
const code = editor46329.getValue(); // Fetch code from the editor
navigator.clipboard.writeText(code).then(() => {
// alert("Code duplicated to clipboard!");
jQuery(".maineditor46329 .copymessage").show();
setTimeout(function() {
jQuery(".maineditor46329 .copymessage").hide();
}, 2000);
}).catch(err => {
console.error("Error duplicating code: ", err);
});
}
function runCode46329() {
var code = editor46329.getSession().getValue();
function closeoutput46329() {
var code = editor46329.getSession().getValue();
jQuery(".maineditor46329 .code-editor-output").hide();
}
// Attach event listeners to the buttons
document.getElementById("copyBtn46329").addEventListener("click", copyCodeToClipboard46329);
document.getElementById("runBtn46329").addEventListener("click", runCode46329);
``````html
runCode46329);
document.getElementById("closeoutputBtn46329").addEventListener("click", closeoutput46329);
Outcome:
Final Thoughts
Throughout this article, we have discovered how to construct arrays, manipulate them, and we have examined various useful methods that facilitate working with arrays efficiently. An array allows for multiple values to be retained within a single variable. It resembles a list where you can organize items like numbers, strings, or other data.
JavaScript Arrays – Common Questions
Q1. What are arrays in JavaScript?
In an array, multiple values reside within a single variable. Each element is positioned at an index, which begins at 0.
Q2. What are the distinct types of arrays?
Essentially, there are two categories of arrays in JavaScript:
1. Single-dimensional array
2. Multi-dimensional array
Q3. How do you generate an array in JavaScript?
An array can be created in two ways: by using array literals ([]) or through the Array constructor.
Q4. What are the most frequently used array methods in JavaScript?
The most utilized array methods in JavaScript include push(), pop(), shift(), unshift(), map(), filter(), forEach(), and sort().
Q5. Can arrays hold various data types in JavaScript?
Indeed, arrays can encompass a variety of data types such as strings, numbers, objects, and additional arrays as well.
To provide the best experiences, we use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us to process data such as browsing behavior or unique IDs on this site. Not consenting or withdrawing consent, may adversely affect certain features and functions.
Functional
Always active
The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.
Preferences
The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.
Statistics
The technical storage or access that is used exclusively for statistical purposes.The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.
Marketing
The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.