Destructuring assignment
The two most used data structures in JavaScript are Object and Array .
- Objects allow us to create a single entity that stores data items by key.
- Arrays allow us to gather data items into an ordered list.
However, when we pass these to a function, we may not need all of it. The function might only require certain elements or properties.
Destructuring assignment is a special syntax that allows us to “unpack” arrays or objects into a bunch of variables, as sometimes that’s more convenient.
Destructuring also works well with complex functions that have a lot of parameters, default values, and so on. Soon we’ll see that.
![](http://sektorel.online/777/templates/cheerup/res/banner1.gif)
Array destructuring
Here’s an example of how an array is destructured into variables:
Now we can work with variables instead of array members.
It looks great when combined with split or other array-returning methods:
As you can see, the syntax is simple. There are several peculiar details though. Let’s see more examples to understand it better.
It’s called “destructuring assignment,” because it “destructurizes” by copying items into variables. However, the array itself is not modified.
It’s just a shorter way to write:
Unwanted elements of the array can also be thrown away via an extra comma:
In the code above, the second element of the array is skipped, the third one is assigned to title , and the rest of the array items are also skipped (as there are no variables for them).
…Actually, we can use it with any iterable, not only arrays:
That works, because internally a destructuring assignment works by iterating over the right value. It’s a kind of syntax sugar for calling for..of over the value to the right of = and assigning the values.
We can use any “assignables” on the left side.
For instance, an object property:
In the previous chapter, we saw the Object.entries(obj) method.
We can use it with destructuring to loop over the keys-and-values of an object:
The similar code for a Map is simpler, as it’s iterable:
There’s a well-known trick for swapping values of two variables using a destructuring assignment:
Here we create a temporary array of two variables and immediately destructure it in swapped order.
We can swap more than two variables this way.
The rest ‘…’
Usually, if the array is longer than the list at the left, the “extra” items are omitted.
For example, here only two items are taken, and the rest is just ignored:
If we’d like also to gather all that follows – we can add one more parameter that gets “the rest” using three dots "..." :
The value of rest is the array of the remaining array elements.
We can use any other variable name in place of rest , just make sure it has three dots before it and goes last in the destructuring assignment.
Default values
If the array is shorter than the list of variables on the left, there will be no errors. Absent values are considered undefined:
If we want a “default” value to replace the missing one, we can provide it using = :
Default values can be more complex expressions or even function calls. They are evaluated only if the value is not provided.
For instance, here we use the prompt function for two defaults:
Please note: the prompt will run only for the missing value ( surname ).
Object destructuring
The destructuring assignment also works with objects.
The basic syntax is:
We should have an existing object on the right side, that we want to split into variables. The left side contains an object-like “pattern” for corresponding properties. In the simplest case, that’s a list of variable names in {...} .
For instance:
Properties options.title , options.width and options.height are assigned to the corresponding variables.
The order does not matter. This works too:
The pattern on the left side may be more complex and specify the mapping between properties and variables.
If we want to assign a property to a variable with another name, for instance, make options.width go into the variable named w , then we can set the variable name using a colon:
The colon shows “what : goes where”. In the example above the property width goes to w , property height goes to h , and title is assigned to the same name.
For potentially missing properties we can set default values using "=" , like this:
Just like with arrays or function parameters, default values can be any expressions or even function calls. They will be evaluated if the value is not provided.
In the code below prompt asks for width , but not for title :
We also can combine both the colon and equality:
If we have a complex object with many properties, we can extract only what we need:
The rest pattern “…”
What if the object has more properties than we have variables? Can we take some and then assign the “rest” somewhere?
We can use the rest pattern, just like we did with arrays. It’s not supported by some older browsers (IE, use Babel to polyfill it), but works in modern ones.
It looks like this:
In the examples above variables were declared right in the assignment: let {…} = {…} . Of course, we could use existing variables too, without let . But there’s a catch.
This won’t work:
The problem is that JavaScript treats {...} in the main code flow (not inside another expression) as a code block. Such code blocks can be used to group statements, like this:
So here JavaScript assumes that we have a code block, that’s why there’s an error. We want destructuring instead.
To show JavaScript that it’s not a code block, we can wrap the expression in parentheses (...) :
Nested destructuring
If an object or an array contains other nested objects and arrays, we can use more complex left-side patterns to extract deeper portions.
In the code below options has another object in the property size and an array in the property items . The pattern on the left side of the assignment has the same structure to extract values from them:
All properties of options object except extra which is absent in the left part, are assigned to corresponding variables:
Finally, we have width , height , item1 , item2 and title from the default value.
Note that there are no variables for size and items , as we take their content instead.
Smart function parameters
There are times when a function has many parameters, most of which are optional. That’s especially true for user interfaces. Imagine a function that creates a menu. It may have a width, a height, a title, an item list and so on.
Here’s a bad way to write such a function:
In real-life, the problem is how to remember the order of arguments. Usually, IDEs try to help us, especially if the code is well-documented, but still… Another problem is how to call a function when most parameters are ok by default.
That’s ugly. And becomes unreadable when we deal with more parameters.
Destructuring comes to the rescue!
We can pass parameters as an object, and the function immediately destructurizes them into variables:
We can also use more complex destructuring with nested objects and colon mappings:
The full syntax is the same as for a destructuring assignment:
Then, for an object of parameters, there will be a variable varName for the property incomingProperty , with defaultValue by default.
Please note that such destructuring assumes that showMenu() does have an argument. If we want all values by default, then we should specify an empty object:
We can fix this by making {} the default value for the whole object of parameters:
In the code above, the whole arguments object is {} by default, so there’s always something to destructurize.
Destructuring assignment allows for instantly mapping an object or array onto many variables.
The full object syntax:
This means that property prop should go into the variable varName and, if no such property exists, then the default value should be used.
Object properties that have no mapping are copied to the rest object.
The full array syntax:
The first item goes to item1 ; the second goes into item2 , and all the rest makes the array rest .
It’s possible to extract data from nested arrays/objects, for that the left side must have the same structure as the right one.
We have an object:
Write the destructuring assignment that reads:
- name property into the variable name .
- years property into the variable age .
- isAdmin property into the variable isAdmin (false, if no such property)
Here’s an example of the values after your assignment:
The maximal salary
There is a salaries object:
Create the function topSalary(salaries) that returns the name of the top-paid person.
- If salaries is empty, it should return null .
- If there are multiple top-paid persons, return any of them.
P.S. Use Object.entries and destructuring to iterate over key/value pairs.
Open a sandbox with tests.
Open the solution with tests in a sandbox.
Lesson navigation
- © 2007—2024 Ilya Kantor
- about the project
- terms of usage
- privacy policy
Home » JavaScript Array Methods » ES6 Destructuring Assignment
ES6 Destructuring Assignment
Summary : in this tutorial, you will learn how to use the ES6 destructuring assignment that allows you to destructure an array into individual variables.
ES6 provides a new feature called destructing assignment that allows you to destructure properties of an object or elements of an array into individual variables.
Let’s start with the array destructuring.
Introduction to JavaScript Array destructuring
Assuming that you have a function that returns an array of numbers as follows:
The following invokes the getScores() function and assigns the returned value to a variable:
To get the individual score, you need to do like this:
Prior to ES6, there was no direct way to assign the elements of the returned array to multiple variables such as x , y and z .
Fortunately, starting from ES6, you can use the destructing assignment as follows:
The variables x , y and z will take the values of the first, second, and third elements of the returned array.
Note that the square brackets [] look like the array syntax but they are not.
If the getScores() function returns an array of two elements, the third variable will be undefined , like this:
In case the getScores() function returns an array that has more than three elements, the remaining elements are discarded. For example:
Array Destructuring Assignment and Rest syntax
It’s possible to take all remaining elements of an array and put them in a new array by using the rest syntax (...) :
The variables x and y receive values of the first two elements of the returned array. And the args variable receives all the remaining arguments, which are the last two elements of the returned array.
Note that it’s possible to destructure an array in the assignment that separates from the variable’s declaration. For example:
Setting default values
See the following example:
How it works:
- First, declare the getItems() function that returns an array of two numbers.
- Then, assign the items variable to the returned array of the getItems() function.
- Finally, check if the third element exists in the array. If not, assign the value 0 to the thirdItem variable.
It’ll be simpler with the destructuring assignment with a default value:
If the value taken from the array is undefined , you can assign the variable a default value, like this:
If the getItems() function doesn’t return an array and you expect an array, the destructing assignment will result in an error. For example:
A typical way to solve this is to fallback the returned value of the getItems() function to an empty array like this:
Nested array destructuring
The following function returns an array that contains an element which is another array, or nested array:
Since the third element of the returned array is another array, you need to use the nested array destructuring syntax to destructure it, like this:
Array Destructuring Assignment Applications
Let’s see some practical examples of using the array destructuring assignment syntax.
1) Swapping variables
The array destructuring makes it easy to swap values of variables without using a temporary variable:
2) Functions that return multiple values
In JavaScript, a function can return a value. However, you can return an array that contains multiple values, for example:
And then you use the array destructuring assignment syntax to destructure the elements of the return array into variables:
In this tutorial, you have learned how to use the ES6 destructuring assignment to destructure elements in an array into individual variables.
JavaScript Arrays: Create, Access, Add & Remove Elements
We have learned that a variable can hold only one value. We cannot assign multiple values to a single variable. JavaScript array is a special type of variable, which can store multiple values using a special syntax.
The following declares an array with five numeric values.
In the above array, numArr is the name of an array variable. Multiple values are assigned to it by separating them using a comma inside square brackets as [10, 20, 30, 40, 50] . Thus, the numArr variable stores five numeric values. The numArr array is created using the literal syntax and it is the preferred way of creating arrays.
Another way of creating arrays is using the Array() constructor, as shown below.
Every value is associated with a numeric index starting with 0. The following figure illustrates how an array stores values.
![javascript array assignment](https://www.tutorialsteacher.com/Content/images/js/array1.png)
The following are some more examples of arrays that store different types of data.
It is not required to store the same type of values in an array. It can store values of different types as well.
Get Size of an Array
Use the length property to get the total number of elements in an array. It changes as and when you add or remove elements from the array.
Accessing Array Elements
Array elements (values) can be accessed using an index. Specify an index in square brackets with the array name to access the element at a particular index like arrayName[index] . Note that the index of an array starts from zero.
For the new browsers, you can use the arr.at(pos) method to get the element from the specified index. This is the same as arr[index] except that the at() returns an element from the last element if the specified index is negative.
You can iterate an array using Array.forEach() , for, for-of, and for-in loop, as shown below.
Update Array Elements
You can update the elements of an array at a particular index using arrayName[index] = new_value syntax.
Adding New Elements
You can add new elements using arrayName[index] = new_value syntax. Just make sure that the index is greater than the last index. If you specify an existing index then it will update the value.
In the above example, cities[9] = "Pune" adds "Pune" at 9th index and all other non-declared indexes as undefined.
The recommended way of adding elements at the end is using the push() method. It adds an element at the end of an array.
Use the unshift() method to add an element to the beginning of an array.
Remove Array Elements
The pop() method returns the last element and removes it from the array.
The shift() method returns the first element and removes it from the array.
You cannot remove middle elements from an array. You will have to create a new array from an existing array without the element you do not want, as shown below.
Learn about array methods and properties in the next chapter.
![javascript array assignment](https://www.tutorialsteacher.com/Content/images/authors/tutorialsteacher.png)
We are a team of passionate developers, educators, and technology enthusiasts who, with their combined expertise and experience, create in -depth, comprehensive, and easy to understand tutorials.We focus on a blend of theoretical explanations and practical examples to encourages hands - on learning. Visit About Us page for more information.
- JavaScript Minifier
- JSON Formatter
- XML Formatter
Popular Tutorials
Popular examples, reference materials, learn python interactively, js introduction.
- Getting Started
- JS Variables & Constants
- JS console.log
- JavaScript Data types
- JavaScript Operators
- JavaScript Comments
- JS Type Conversions
JS Control Flow
- JS Comparison Operators
- JavaScript if else Statement
- JavaScript for loop
- JavaScript while loop
- JavaScript break Statement
- JavaScript continue Statement
- JavaScript switch Statement
JS Functions
- JavaScript Function
- Variable Scope
- JavaScript Hoisting
- JavaScript Recursion
- JavaScript Objects
- JavaScript Methods & this
- JavaScript Constructor
- JavaScript Getter and Setter
- JavaScript Prototype
JavaScript Array
- JS Multidimensional Array
- JavaScript String
- JavaScript for...in loop
- JavaScript Number
- JavaScript Symbol
Exceptions and Modules
- JavaScript try...catch...finally
- JavaScript throw Statement
- JavaScript Modules
- JavaScript ES6
- JavaScript Arrow Function
- JavaScript Default Parameters
- JavaScript Template Literals
JavaScript Spread Operator
- JavaScript Map
- JavaScript Set
- Destructuring Assignment
- JavaScript Classes
- JavaScript Inheritance
- JavaScript for...of
- JavaScript Proxies
JavaScript Asynchronous
- JavaScript setTimeout()
- JavaScript CallBack Function
- JavaScript Promise
- Javascript async/await
- JavaScript setInterval()
Miscellaneous
- JavaScript JSON
- JavaScript Date and Time
- JavaScript Closure
- JavaScript this
- JavaScript use strict
- Iterators and Iterables
- JavaScript Generators
- JavaScript Regular Expressions
- JavaScript Browser Debugging
- Uses of JavaScript
JavaScript Tutorials
- JavaScript Array splice()
- JavaScript Array shift()
- JavaScript Array unshift()
JavaScript Multidimensional Array
- JavaScript Array pop()
- JavaScript Array slice()
An array is an object that can store multiple values at once.
In the above example, we created an array to record the age of five students.
![Array of Five Elements Array of Five Elements](https://www.programiz.com/sites/tutorial2program/files/javascript-array_1.png)
Why Use Arrays?
Arrays allow us to organize related data by grouping them within a single variable.
Suppose you want to store a list of fruits. Using only variables, this process might look like this:
Here, we've only listed a few fruits. But what if we need to store 100 fruits?
For such a case, the easiest solution is to store them in an array.
An array can store many values in a single variable, making it easy to access them by referring to the corresponding index number.
- Create an Array
We can create an array by placing elements inside an array literal [] , separated by commas. For example,
- numbers - Name of the array.
- [10, 30, 40, 60, 80] - Elements of the array.
Here are a few examples of JavaScript arrays:
Note: Unlike many other programming languages, JavaScript allows us to create arrays with mixed data types.
- Access Elements of an Array
Each element of an array is associated with a number called an index , which specifies its position inside the array.
Consider the following array:
Here is the indexing of each element:
![Index of Array Elements Index of Array Elements](https://www.programiz.com/sites/tutorial2program/files/javascript-array-index_1.png)
We can use an array index to access the elements of the array.
Code | Description |
---|---|
Accesses the first element . | |
Accesses the second element . | |
Accesses the third element . | |
Accesses the fourth element . | |
Accesses the fifth element . |
Let's look at an example.
Remember: Array indexes always start with 0 , not 1.
- Add Element to an Array
We can add elements to an array using built-in methods like push() and unshift() .
1. Using the push() Method
The push() method adds an element at the end of the array.
2. Using the unshift() Method
The unshift() method adds an element at the beginning of the array.
To learn more, visit Array push() and Array unshift() .
- Change the Elements of an Array
We can add or change elements by accessing the index value. For example,
Here, we changed the array element in index 1 (second element) from work to exercise .
- Remove Elements From an Array
We can remove an element from any specified index of an array using the splice() method.
In this example, we removed the element at index 2 (the third element) using the splice() method.
Notice the following code:
Here, (2, 1) means that the splice() method deletes one element starting from index 2 .
Note: Suppose you want to remove the second, third, and fourth elements. You can use the following code to do so:
To learn more, visit JavaScript Array splice() .
- Array Methods
JavaScript has various array methods to perform useful operations. Some commonly used array methods in JavaScript are:
Method | Description |
---|---|
Joins two or more arrays and returns a result. | |
Converts an array to a string of (comma-separated) array values. | |
Searches an element of an array and returns its position (index). | |
Returns the first value of the array element that passes a given test. | |
Returns the first index of the array element that passes a given test. | |
Calls a function for each element. | |
Checks if an array contains a specified element. | |
Sorts the elements alphabetically in strings and ascending order in numbers. | |
Selects part of an array and returns it as a new array. | |
Removes or replaces existing elements and/or adds new elements. |
To learn more, visit JavaScript Array Methods .
More on Javascript Array
You can also create an array using JavaScript's new keyword. For example,
Note : It's better to create an array using an array literal [] for greater readability and execution speed.
We can remove an element from an array using built-in methods like pop() and shift() .
1. Remove the last element using pop().
2. Remove the first element using shift().
To learn more, visit Array pop() and Array shift() .
We can find the length of an array using the length property. For example,
In JavaScript, arrays are a type of object. However,
- Arrays use numbered indexes to access elements.
- Objects use named indexes (keys) to access values.
Since arrays are objects, the array elements are stored by reference . Hence, when we assign an array to another variable, we are just pointing to the same array in memory.
So, changing one will change the other because they're essentially the same array. For example,
Here, we modified the copied array arr1 , which also modified the original array arr .
- JavaScript forEach
Table of Contents
- Introduction
Sorry about that.
Related Tutorials
JavaScript Tutorial
JavaScript forEach()
JavaScript Set and WeakSet
JS Tutorial
Js versions, js functions, js html dom, js browser bom, js web apis, js vs jquery, js graphics, js examples, js references, javascript assignment, javascript assignment operators.
Assignment operators assign values to JavaScript variables.
Operator | Example | Same As |
---|---|---|
= | x = y | x = y |
+= | x += y | x = x + y |
-= | x -= y | x = x - y |
*= | x *= y | x = x * y |
/= | x /= y | x = x / y |
%= | x %= y | x = x % y |
**= | x **= y | x = x ** y |
Shift Assignment Operators
Operator | Example | Same As |
---|---|---|
<<= | x <<= y | x = x << y |
>>= | x >>= y | x = x >> y |
>>>= | x >>>= y | x = x >>> y |
Bitwise Assignment Operators
Operator | Example | Same As |
---|---|---|
&= | x &= y | x = x & y |
^= | x ^= y | x = x ^ y |
|= | x |= y | x = x | y |
Logical Assignment Operators
Operator | Example | Same As |
---|---|---|
&&= | x &&= y | x = x && (x = y) |
||= | x ||= y | x = x || (x = y) |
??= | x ??= y | x = x ?? (x = y) |
The = Operator
The Simple Assignment Operator assigns a value to a variable.
Simple Assignment Examples
The += operator.
The Addition Assignment Operator adds a value to a variable.
Addition Assignment Examples
The -= operator.
The Subtraction Assignment Operator subtracts a value from a variable.
Subtraction Assignment Example
The *= operator.
The Multiplication Assignment Operator multiplies a variable.
Multiplication Assignment Example
The **= operator.
The Exponentiation Assignment Operator raises a variable to the power of the operand.
Exponentiation Assignment Example
The /= operator.
The Division Assignment Operator divides a variable.
Division Assignment Example
The %= operator.
The Remainder Assignment Operator assigns a remainder to a variable.
Remainder Assignment Example
Advertisement
The <<= Operator
The Left Shift Assignment Operator left shifts a variable.
Left Shift Assignment Example
The >>= operator.
The Right Shift Assignment Operator right shifts a variable (signed).
Right Shift Assignment Example
The >>>= operator.
The Unsigned Right Shift Assignment Operator right shifts a variable (unsigned).
Unsigned Right Shift Assignment Example
The &= operator.
The Bitwise AND Assignment Operator does a bitwise AND operation on two operands and assigns the result to the the variable.
Bitwise AND Assignment Example
The |= operator.
The Bitwise OR Assignment Operator does a bitwise OR operation on two operands and assigns the result to the variable.
Bitwise OR Assignment Example
The ^= operator.
The Bitwise XOR Assignment Operator does a bitwise XOR operation on two operands and assigns the result to the variable.
Bitwise XOR Assignment Example
The &&= operator.
The Logical AND assignment operator is used between two values.
If the first value is true, the second value is assigned.
Logical AND Assignment Example
The &&= operator is an ES2020 feature .
The ||= Operator
The Logical OR assignment operator is used between two values.
If the first value is false, the second value is assigned.
Logical OR Assignment Example
The ||= operator is an ES2020 feature .
The ??= Operator
The Nullish coalescing assignment operator is used between two values.
If the first value is undefined or null, the second value is assigned.
Nullish Coalescing Assignment Example
The ??= operator is an ES2020 feature .
Test Yourself With Exercises
Use the correct assignment operator that will result in x being 15 (same as x = x + y ).
Start the Exercise
![javascript array assignment Get Certified](https://www.w3schools.com/images/img_fullaccess_up_sep1_green_300.png)
COLOR PICKER
![javascript array assignment colorpicker](https://www.w3schools.com/images/colorpicker2000.png)
Contact Sales
If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]
![](http://sektorel.online/777/templates/cheerup/res/banner1.gif)
Report Error
If you want to report an error, or if you want to make a suggestion, send us an e-mail: [email protected]
Top Tutorials
Top references, top examples, get certified.
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
Assignment (=)
The assignment ( = ) operator is used to assign a value to a variable or property. The assignment expression itself has a value, which is the assigned value. This allows multiple assignments to be chained in order to assign a single value to multiple variables.
A valid assignment target, including an identifier or a property accessor . It can also be a destructuring assignment pattern .
An expression specifying the value to be assigned to x .
Return value
The value of y .
Thrown in strict mode if assigning to an identifier that is not declared in the scope.
Thrown in strict mode if assigning to a property that is not modifiable .
Description
The assignment operator is completely different from the equals ( = ) sign used as syntactic separators in other locations, which include:
- Initializers of var , let , and const declarations
- Default values of destructuring
- Default parameters
- Initializers of class fields
All these places accept an assignment expression on the right-hand side of the = , so if you have multiple equals signs chained together:
This is equivalent to:
Which means y must be a pre-existing variable, and x is a newly declared const variable. y is assigned the value 5 , and x is initialized with the value of the y = 5 expression, which is also 5 . If y is not a pre-existing variable, a global variable y is implicitly created in non-strict mode , or a ReferenceError is thrown in strict mode. To declare two variables within the same declaration, use:
Simple assignment and chaining
Value of assignment expressions.
The assignment expression itself evaluates to the value of the right-hand side, so you can log the value and assign to a variable at the same time.
Unqualified identifier assignment
The global object sits at the top of the scope chain. When attempting to resolve a name to a value, the scope chain is searched. This means that properties on the global object are conveniently visible from every scope, without having to qualify the names with globalThis. or window. or global. .
Because the global object has a String property ( Object.hasOwn(globalThis, "String") ), you can use the following code:
So the global object will ultimately be searched for unqualified identifiers. You don't have to type globalThis.String ; you can just type the unqualified String . To make this feature more conceptually consistent, assignment to unqualified identifiers will assume you want to create a property with that name on the global object (with globalThis. omitted), if there is no variable of the same name declared in the scope chain.
In strict mode , assignment to an unqualified identifier in strict mode will result in a ReferenceError , to avoid the accidental creation of properties on the global object.
Note that the implication of the above is that, contrary to popular misinformation, JavaScript does not have implicit or undeclared variables. It just conflates the global object with the global scope and allows omitting the global object qualifier during property creation.
Assignment with destructuring
The left-hand side of can also be an assignment pattern. This allows assigning to multiple variables at once.
For more information, see Destructuring assignment .
Specifications
Specification |
---|
Browser compatibility
BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.
- Assignment operators in the JS guide
- Destructuring assignment
- DSA with JS - Self Paced
- JS Tutorial
- JS Exercise
- JS Interview Questions
- JS Operator
- JS Projects
- JS Examples
- JS Free JS Course
- JS A to Z Guide
- JS Formatter
JavaScript Arrays
An array in JavaScript is a data structure used to store multiple values in a single variable. It can hold various data types and allows for dynamic resizing. Elements are accessed by their index, starting from 0.
![javascript array assignment JavaScript Arrays](https://media.geeksforgeeks.org/wp-content/uploads/20240116154803/JavaScript-Array.webp)
JavaScript Array
You have two ways to create JavaScript Arrays: using the Array constructor or the shorthand array literal syntax , which is just square brackets. Arrays are flexible in size, so they can grow or shrink as you add or remove elements.
Table of Content
Basic Terminologies of JavaScript Array
Declaration of an array, basic operations on javascript arrays, difference between javascript arrays and objects, when to use javascript arrays and objects, recognizing a javascript array, javascript array complete reference, javascript array examples, javascript cheatsheet.
- Array: A data structure in JavaScript that allows you to store multiple values in a single variable.
- Array Element: Each value within an array is called an element. Elements are accessed by their index.
- Array Index: A numeric representation that indicates the position of an element in the array. JavaScript arrays are zero-indexed, meaning the first element is at index 0.
- Array Length: The number of elements in an array. It can be retrieved using the length property.
There are basically two ways to declare an array i.e. Array Literal and Array Constructor.
1. Creating an Array using Array Literal
Creating an array using array literal involves using square brackets [] to define and initialize the array. This method is concise and widely preferred for its simplicity.
2. Creating an Array using JavaScript new Keyword (Array Constructor)
The “ Array Constructor ” refers to a method of creating arrays by invoking the Array constructor function. This approach allows for dynamic initialization and can be used to create arrays with a specified length or elements.
Note: Both the above methods do exactly the same. Use the array literal method for efficiency, readability, and speed.
1. Accessing Elements of an Array
Any element in the array can be accessed using the index number. The index in the arrays starts with 0.
2. Accessing the First Element of an Array
The array indexing starts from 0, so we can access first element of array using the index number.
3. Accessing the Last Element of an Array
We can access the last array element using [array.length – 1] index number.
4. Modifying the Array Elements
Elements in an array can be modified by assigning a new value to their corresponding index.
5. Adding Elements to the Array
Elements can be added to the array using methods like push() and unshift() .
- The push() method add the element to the end of the array.
- The unshift() method add the element to the starting of the array.
6. Removing Elements from an Array
To remove the elements from an array we have different methods like pop() , shift() , or splice() .
- The pop() method removes an element from the last index of the array.
- The shift() method removes the element from the first index of the array.
- The splice() method removes or replaces the element from the array.
7. Array Length
We can get the length of the array using the array length property .
8. Increase and Decrease the Array Length
We can increase and decrease the array length using the JavaScript length property.
9. Iterating Through Array Elements
We can iterate array and access array elements using for loop and forEach loop.
Example: It is an example of for loop.
Example: It is the example of Array.forEach() loop.
10. Array Concatenation
Combine two or more arrays using the concat() method. It returns new array containing joined arrays elements.
11. Conversion of an Array to String
We have a builtin method toString() to converts an array to a string.
12. Check the Type of an Arrays
The JavaScript typeof operator is used ot check the type of an array. It returns “object” for arrays.
Feature | JavaScript Arrays | JavaScript Objects |
---|---|---|
Numeric indexes (0, 1, 2, …) | Named keys (strings or symbols) | |
Ordered collection | Unordered collection | |
Storing lists, sequences, ordered data | Storing data with key-value pairs, attributes | |
Accessed by index (e.g., arr[0]) | Accessed by key (e.g., obj[“key”]) | |
Typically iterated using loops like for or forEach | Iterated using for…in, Object.keys(), or Object.entries() | |
Dynamic, can grow or shrink in size | Dynamic, can add or remove key-value pairs |
- Use arrays when you need numeric indexing and order matters.
- Use objects when you need named keys and the relationship between keys and values is important.
There are two methods by which we can recognize a JavaScript array:
- By using Array.isArray() method
- By using instanceof method
Below is an example showing both approaches:
Note: A common error is faced while writing the arrays:
The above two statements are not the same.
Output: This statement creates an array with an element ” [5] “.
We have a complete list of Javascript Array, to check those please go through this JavaScript Array Reference article. It contains a detailed description and examples of all Array Properties and Methods.
JavaScript Array examples contain a list of questions that are majorly asked in interviews. Please check this article JavaScript Array Examples for more detail.
We have a Cheat Sheet on Javascript where we have covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript .
JavaScript Arrays – FAQs
What is an array in javascript.
An array is a special type of object used to store multiple values in a single variable. Arrays can hold any combination of data types, including numbers, strings, objects, and even other arrays.
How do you create an array?
You can create an array using the array literal syntax or the Array constructor.
What is the array literal syntax?
The array literal syntax uses square brackets to enclose a comma-separated list of values. Example: const fruits = [“apple”, “banana”, “cherry”];
What is the Array constructor?
The Array constructor creates an array by using the new Array() syntax. Example: const fruits = new Array(“apple”, “banana”, “cherry”);
How do you access array elements?
You can access array elements using their index, which starts at 0 for the first element. Example: const firstFruit = fruits[0];
How do you modify array elements?
You can modify array elements by assigning a new value to a specific index. Example: fruits[0] = “orange”;
Please Login to comment...
Similar reads.
- Web Technologies
- javascript-array
- Web technologies
Improve your Coding Skills with Practice
What kind of Experience do you want to share?
How to Manipulate Arrays in JavaScript
![javascript array assignment Bolaji Ayodeji](https://www.freecodecamp.org/news/content/images/size/w60/2024/01/avatar.jpg)
An important part of any programming language. Most times we need to do several operations on arrays, hence this article.
In this article, I would show you various methods of manipulating arrays in JavaScript [^^]
What are Arrays in JavaScript?
Before we proceed, you need to understand what arrays really mean.
In JavaScript, an array is a variable that is used to store different data types. It basically stores different elements in one box and can be later assesssed with the variable.
Declaring an array:
Arrays can contain multiple data types
Arrays can be manipulated by using several actions known as methods. Some of these methods allow us to add, remove, modify and do lots more to arrays.
I would be showing you a few in this article, let’s roll :)
NB: I used Arrow functions in this post, If you don’t know what this means, you should read here . Arrow function is an ES6 feature .
The JavaScript method toString() converts an array to a string separated by a comma.
The JavaScript join() method combines all array elements into a string.
It is similar to toString() method, but here you can specify the separator instead of the default comma.
This method combines two arrays together or add more items to an array and then return a new array.
This method adds items to the end of an array and changes the original array.
This method removes the last item of an array and returns it.
This method removes the first item of an array and returns it.
This method adds an item(s) to the beginning of an array and changes the original array.
You can also add multiple items at once
This method changes an array, by adding, removing and inserting elements.
The syntax is:
- Index here is the starting point for removing elements in the array
- deleteCount is the number of elements to be deleted from that index
- element1, …, elementN is the element(s) to be added
Removing items
after running splice() , it returns the array with the item(s) removed and removes it from the original array.
NB : The deleteCount does not include the last index in range.
If the second parameter is not declared, every element starting from the given index will be removed from the array:
In the next example we will remove 3 elements from the array and replace them with more items:
Adding items
To add items, we need to set the deleteCount to zero
This method is similar to splice() but very different. It returns subarrays instead of substrings.
This method copies a given part of an array and returns that copied part as a new array. It does not change the original array.
Here’s a basic example:
The best way to use slice() is to assign it to a new variable.
This method is used for strings . It divides a string into substrings and returns them as an array.
Here’s the syntax:string.split(separator, limit);
- The separator here defines how to split a string either by a comma.
- The limit determines the number of splits to be carried out
another example:
NB: If we declare an empty array, like this firstName.split(''); then each item in the string will be divided as substrings :
This method looks for an item in an array and returns the index where it was found else it returns -1
lastIndexOf()
This method works the same way indexOf() does except that it works from right to left. It returns the last index where the item was found
This method creates a new array if the items of an array pass a certain condition.
Checks users from Nigeria
This method creates a new array by manipulating the values in an array.
Displays usernames on a page. (Basic friend list display)
![javascript array assignment 1*obuBZKFb5vKmUP7D4TX2XA](https://cdn-media-1.freecodecamp.org/images/1*obuBZKFb5vKmUP7D4TX2XA.png)
This method is good for calculating totals.
reduce() is used to calculate a single value based on an array.
To loop through an array and sum all numbers in the array up, we can use the for of loop.
Here’s how to do same with reduce()
If you omit the initial value, the total will by default start from the first item in the array.
The snippet below shows how the reduce() method works with all four arguments.
source: MDN Docs
![javascript array assignment 1*Cbd9qR_vy71qZjEQCFpCLQ](https://cdn-media-1.freecodecamp.org/images/1*Cbd9qR_vy71qZjEQCFpCLQ.png)
More insights into the reduce() method and various ways of using it can be found here and here .
This method is good for iterating through an array.
It applies a function on all items in an array
iteration can be done without passing the index argument
This method checks if all items in an array pass the specified condition and return true if passed, else false .
check if all numbers are positive
This method checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
c hecks if at least one number is positive
This method checks if an array contains a certain item. It is similar to .some() , but instead of looking for a specific condition to pass, it checks if the array contains a specific item.
If the item is not found, it returns false
There are more array methods, this is just a few of them. Also, there are tons of other actions that can be performed on arrays, try checking MDN docs here for deeper insights.
- toString() converts an array to a string separated by a comma.
- join() combines all array elements into a string.
- concat combines two arrays together or add more items to an array and then return a new array.
- push() adds item(s) to the end of an array and changes the original array.
- pop() removes the last item of an array and returns it
- shift() removes the first item of an array and returns it
- unshift() adds an item(s) to the beginning of an array and changes the original array.
- splice() c hanges an array, by adding, removing and inserting elements.
- slice() copies a given part of an array and returns that copied part as a new array. It does not change the original array.
- split() divides a string into substrings and returns them as an array.
- indexOf() looks for an item in an array and returns the index where it was found else it returns -1
- lastIndexOf() looks for an item from right to left and returns the last index where the item was found.
- filter() creates a new array if the items of an array pass a certain condition.
- map() creates a new array by manipulating the values in an array.
- reduce() calculates a single value based on an array.
- forEach() iterates through an array, it applies a function on all items in an array
- every() checks if all items in an array pass the specified condition and return true if passed, else false.
- some() checks if an item (one or more) in an array pass the specified condition and return true if passed, else false.
- includes() checks if an array contains a certain item.
Let’s wrap it here; Arrays are powerful and using methods to manipulate them creates the Algorithms real-world applications use.
Let's do a create a small function, one that converts a post title into a urlSlug.
URL slug is the exact address of a specific page or post on your site.
When you write an article on Freecodecamp News or any other writing platform, your post title is automatically converted to a slug with white spaces removed, characters turned to lowercase and each word in the title separated by a hyphen.
Here’s a basic function that does that using some of the methods we learnt just now.
in postUrl , we convert the string to lowercase then we use the split() method to convert the string into substrings and returns it in an array
in post slug we join the returned array with a hyphen and then concatenate it to the category string and main url .
That’s it, pretty simple, right? :)
If you’re just getting started with JavaScript, you should check this repository here , I’m compiling a list of basic JavaScript snippets ranging from
- Control flow
Don’t forget to Star and share! :)
PS: This article was first published on my blog here
Software Engineer, Content Creator, Teacher, and Developer Advocate.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
- Artificial Intelligence
- Generative AI
- Cloud Computing
- Data Management
- Emerging Technology
- Technology Industry
- Software Development
- Microsoft .NET
- Development Tools
- Open Source
- Programming Languages
- Enterprise Buyer’s Guides
- Newsletters
- Foundry Careers
- Terms of Service
- Privacy Policy
- Cookie Policy
- Copyright Notice
- Member Preferences
- About AdChoices
- E-commerce Affiliate Relationships
- Your California Privacy Rights
Our Network
- Computerworld
- Network World
![javascript array assignment Matthew Tyson](https://www.infoworld.com/wp-content/uploads/2024/08/2019-0-18942200-1724230854-author_photo_Matthew-Tyson_1651612766.jpeg?quality=50&strip=all&w=116)
State of JavaScript: Insights from the latest JavaScript developer survey
The annual state of javascript survey is one of the best ways to keep your finger on the pulse of what's new and noteworthy in the world of javascript. here's the rundown from the most recent survey..
![javascript array assignment Viewing, surveying, looking ahead. Young man with binoculars and map in hand.](https://www.infoworld.com/wp-content/uploads/2024/08/3486850-0-81606600-1724230864-shutterstock_2470662585.jpg?quality=50&strip=all&w=1024)
It can sometimes be overwhelming keeping up with everything happening in the world of JavaScript , but I think JavaScript developers mostly know we are lucky. We get to work in a space where smart people are constantly generating new ideas. We are surrounded by peers who are freely available and actively engaged, a high-water mark in open source creativity.
There are various ways to stay abreast of the changing JavaScript landscape , but possibly the most comprehensive is to watch for the results of the annual State of the JavaScript survey. This rite of self-reflection by the JavaScript community combines breadth and depth along with a practical sense of which JavaScript tools and features are being actively used by coders all over the world.
The results of the 2023 State of JavaScript survey were recently released. Let’s crack it open and take a look.
Strong types in JavaScript
It’s a great irony, but the biggest language “pain point” for JavaScript is the lack of strong typing. The flexible straightforwardness of JavaScript’s native duck-typing is one of the things that has made it so wildly popular. But there are also many benefits to strong typing, and some JavaScript developers really want them! Even with the option of TypeScript, a full one third of survey respondents said they would like to see static typing in JavaScript.
The interesting question then becomes: will we ever see types adopted into the ECMAScript language specification? It looks like we will but it’s hard to say when. See the ECMAScript proposal: Type Annotations for more about how and when strong types might be added to JavaScript.
Meta frameworks
Meta-frameworks are frameworks that combine a reactive front end like React or Vue within a larger system that includes a server-side and related features. Needless to say, such frameworks are extremely popular.
Next.js is the leading meta-framework, holding a strong first position . But several lower profile frameworks are duking it out and gaining mindshare. Forty-four percent of JavaScript survey respondents indicated they had used and would use Next.js again. Its one-time close competitor, Gatsby , has fallen away with only 5% saying they would use it. Nuxt (the Vue version of Next.js), Astro , and SvelteKit are neck-and-neck at 18%, 17%, 16% respectively. Remix (8%), Docusaurus (7%), Eleventy (3%), and Deno Fresh (2.16%) currently bring up the rear in framework popularity.
Seeing Astro among the top five JavaScript meta-frameworks raised an eyebrow. I’ve watched this project for a while (see Intro to Astro: Clever lazy loading for JavaScript ) but its leading place on the survey suggests Astro is moving into the mainstream. I also was surprised by the emergence of Deno Fresh . Deno is the spiritual successor to Node.js and was also created by Node’s progenitor, Ryan Dahl . But it was news to me that Deno now includes a front-end meta framework. It is on my list to check it out.
Front-end frameworks
Pure front-end frameworks are rather predictable suspects at this point. React clearly leads the pack, with 65% of survey respondents expressing the “used it, want to use again” sentiment. Vue (38%), Svelte (22%), and Angular (20%) are the other leading front-end frameworks currently. Svelte taking the lead over Angular is the most interesting story there.
While its real-world popularity is growing, Svelte remains an untried (that is, “heard of it, want to try it”) option for 48% of respondents. Awareness of HTMX is also growing, with 37% of respondents saying they want to try it.
Stencil is an interesting outlier in this field, with 59% of respondents saying they’ve never heard of it.
Build tools
WebPack remains a popular and well-liked build pipeline, while Vite is seeing an extraordinary rise in usage and satisfaction.
Vite’s rating on the “Used it and want to use it again” chart is an impressive 72%. WebPack holds a 48% ranking by the same measure. The difference between the two probably reflects Vite being specifically designed to improve on the previous generation of build tools like WebPack. These numbers may also reflect the reality that the more a tool is used, the more gripes people tend to have with it. Users tend become increasingly aware of and grumpy about a tool’s flaws with extended use. As tools become more established, they are also embedded into more projects, whether we like it or not.
That latter consideration probably figures large in the dissatisfaction (“negative sentiment”) from previous users, where WebPack shows a whopping 48% negative experience versus 1.34% for Vite.
The TypeScript command-line tooling (TSC CLI) seems to have peaked a couple of years ago and ranks at a still respectable 43% in the “used it, would use again” category. Additional build tools considered are Rollup, Parcel, SWC, TurboPack, tsup, and Biome. If you think that’s a lot of build tools for JavaScript, you are not alone!
It’s also notable that the Bun bundler dominates in the “Other build tools” section, with 51% of users giving it a positive rating.
Anywhere you run JavaScript, that’s a runtime . It was a surprise to me that Node is now a more popular runtime than web browsers, at 94% versus 83%. That is really something. Less surprising but still remarkable is the rocket ship that is Bun.js , now representing 23% of runtime users. That is astounding for a project that only reached version 1.0 in September of 2023.
Service workers (20%), Deno (15%), Hermes (4%), and ChakraCore (.5%) round out the field. Those numbers highlight the growing use of service workers and the steady adoption of Deno.
A very interesting tale is unfolding among hosting services, wherein Vercel is challenging AWS’s dominance. The “Which of these services have you used to host JavaScript apps?” question shows AWS at 47% to Vercel’s 45%. This is followed closely with GitHub pages at 42%. Netlify (33%), Heroku (25%), Cloudflare (20%), Digital Ocean (20%), Azure (19%), and Google Cloud (18%) are also all well represented.
Things to learn about JavaScript
The latest survey introduces a reading list that lets readers save topics they want to learn more about. This is a nice feature when taking the survey and also provides insight into features other JavaScript users are interested in. This is a good page to look at to get a sense of what you might want to learn about yourself.
The top of the list is error.cause (44%), which makes sense because it is a newer feature, and one that is simple and commonly needed. Logical assignment (38%) is another newer language feature that allows setting variables based on a unary logical operation. Other interesting items include Hashbang grammar (35%) and array.with (34%).
Other languages
JavaScript developers use a whole universe of other languages. Python leads the pack at 44%, not surprising given its use in machine learning and data analytics. PHP (31%), Java (27%), and C# (25%) still are strong favorites for JavaScript developers. Shell scripting languages are neck-and-neck with Bash (22%), Go (21%), and Rust (20%) taking the lead.
Among monorepos , pnpm has pulled away from the pack with 40% usage and 64% positivity. Bun again sees strong write-in support with 54% percent of respondents writing it in. Another newcomer, called Moon was written in by 14% of respondents to this question.
Retention versus usage
A great chart for an overview of the field is Retention vs. use . The chart gives you a grid with retention on one axis and the number of users on the other. It’s a fun chart to explore looking for things you have used or might want to learn about.
Vitetest is high on retention with a considerable way to go in usage. React shows strong numbers on both counts, with retention at 76%. Tauri shows 91% retention. On the other end of things, the cross-platform framework Cordova , shows only 15% retention. Gatsby is not much better at 21%.
Jest has established and held its place as the most-used testing framework since 2019. Storybook is also much used at 53%. Cypress and Mocha are in a virtual tie around 48%. Puppeteer and the literally named Testing Library both hover around 40%. Vitatest is breaking out, having risen from 14% to 34% over the past year.
Probably the biggest takeaway from this year’s State of JavaScript survey is how active the space still is. There really aren’t any areas of JavaScript not seeing innovation and change. Besides the ongoing stability of React, it looks like an open field where almost anything can happen and probably will. If you were thinking of building something for JavaScript developers to use in their work, go for it!
On the other hand, if you are trying to decide on a technology to use in your work, the changing landscape and wealth of choices can make it difficult. In fact, 10% of respondents noted “choice overload” as a JavaScript pain point. Using the survey to stay on top of trends and new technologies is a good practice to avoid overload and ensure you are choosing from among the best tools available.
Related content
Api security starts with api discovery, java polymorphism and its types, microsoft .net 9 previews c#, runtime, sdk improvements.
![javascript array assignment Matthew Tyson](https://www.infoworld.com/wp-content/uploads/2024/08/2019-0-18942200-1724230854-author_photo_Matthew-Tyson_1651612766.jpeg?quality=50&strip=all&w=116)
Matthew Tyson is a founder of Dark Horse Group, Inc. He believes in people-first technology. When not playing guitar, Matt explores the backcountry and the philosophical hinterlands. He has written for JavaWorld since 2007.
More from this author
Functional programming with java collections, full-stack development with java, react, and spring boot, part 3, full-stack development with java, react, and spring boot, part 2, full-stack development with java, react, and spring boot, part 1, frequently sought solutions for javascript, progressive web app essentials: service worker background sync, intro to multithreaded javascript, stream gatherers: a new way to manipulate java streams, most popular authors.
![javascript array assignment javascript array assignment](https://www.infoworld.com/wp-content/uploads/2024/08/482983-0-08147700-1724182836-paulkrill_crop-100796855-orig.jpg?quality=50&strip=all&w=484)
Show me more
Microsoft’s new phi 3.5 llm models surpass meta and google.
![javascript array assignment Image](https://www.infoworld.com/wp-content/uploads/2024/08/3489654-0-15564500-1724237584-shutterstock_2284126663-100943536-orig-100962531-orig.jpg?quality=50&strip=all&w=375)
3 languages changing data science
![javascript array assignment Image](https://www.infoworld.com/wp-content/uploads/2024/08/3486164-0-84023000-1724229072-shutterstock_2426045505.jpg?quality=50&strip=all&w=375)
The basics of Pillow, Python's image manipulation library
![javascript array assignment Image](https://www.infoworld.com/wp-content/uploads/2024/08/3480797-0-15076600-1723830721-Youtube-Thumbnails_Template-OLD.jpg?quality=50&strip=all&w=444)
How to use the watch command
![javascript array assignment Image](https://www.infoworld.com/wp-content/uploads/2024/08/3479099-0-77926700-1723830335-Linux-Tips-video-template_9673e7.png?w=444)
How to use dbm to stash data quickly in Python
![javascript array assignment Image](https://www.infoworld.com/wp-content/uploads/2024/07/Youtube-Thumbnails_Template-OLD-1.png?w=444)
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Advertising & Talent Reach devs & technologists worldwide about your product, service or employer brand
- OverflowAI GenAI features for Teams
- OverflowAPI Train & fine-tune LLMs
- Labs The future of collective knowledge sharing
- About the company Visit the blog
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Get early access and see previews of new features.
How can I create a two dimensional array in JavaScript?
I have been reading online and some places say it isn't possible, some say it is and then give an example and others refute the example, etc.
How do I declare a 2 dimensional array in JavaScript? (assuming it's possible)
How would I access its members? ( myArray[0][1] or myArray[0,1] ?)
- multidimensional-array
- 27 Assuming a somewhat pedantic definition, it is technically impossible to create a 2d array in javascript. But you can create an array of arrays, which is tantamount to the same. – I. J. Kennedy Commented Jul 29, 2014 at 5:05
- 23 FYI... when you fill an array with more arrays using var arr2D = new Array(5).fill(new Array(3)); , each element of Array(5) will point to the same Array(3). So it's best to use a for loop to dynamically populate sub arrays. – Josh Stribling Commented May 23, 2016 at 8:51
- 93 a = Array(5).fill(0).map(x => Array(10).fill(0)) – Longfei Wu Commented Mar 25, 2017 at 14:21
- 5 In other words, fill doesn't call new Array(3) for each index of the array being filled, since it's not a lambda expression or anything, such as Longfei Wu's comment above, which initially fills the array with 0's, then uses the map function with a lambda to fill each element with a new array. The fill function simply fills the array with exactly what you tell it to. Does that make sense? For more info on the map function, see: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… – Josh Stribling Commented Sep 16, 2017 at 5:38
- 2 @kalehmann that is fine: meta.stackoverflow.com/a/252017/2311074 If the new question is a better question or has better answers, then vote to close the old one as a duplicate of the new one. – Adam Commented Aug 14, 2019 at 6:49
56 Answers 56
Practically? Yes. You can create an array of arrays which functions as an 2D array as every item is an array itself: let items = [ [1, 2], [3, 4], [5, 6] ]; console.log(items[0][0]); // 1 console.log(items[0][1]); // 2 console.log(items[1][0]); // 3 console.log(items[1][1]); // 4 console.log(items);
But technically this is just an array of arrays and not a “true” 2D array, as I. J. Kennedy pointed out.
It should be noted that you could keep nesting arrays into one another and so create “multidimensional” arrays.
![javascript array assignment A-Tech's user avatar](https://i.sstatic.net/bgHwU.png?s=64)
- 44 It would be difficult to initialize a large multidimensional array this way. However, this function can be used to create an empty multidimensional, with the dimensions specified as parameters. – Anderson Green Commented Apr 6, 2013 at 16:49
- 5 @AndersonGreen It's a good thing you mentioned a link for those interested in multi-D array solution, but the question and Ballsacian1's answer are about "2D" array, not "multi-D" array – evilReiko Commented Jun 14, 2014 at 9:56
- 2 @SashikaXP, this does not work for first indices other than 0. – Michael F Commented Dec 30, 2015 at 17:55
- 2 The question is how to declare a two dimensional array. Which is what I was looking for and found this and following answers which fail to discern the difference between declare and initialize. There's also declaration with known length or unbounded, neither of which is discussed. – chris Commented May 30, 2016 at 1:20
- 1 I believe this is a jagged array (array of arrays) - Does JavaScript have a difference between jagged and multidimensional as some other languages do? – Luke T O'Brien Commented Sep 3, 2016 at 21:11
You simply make each item within the array an array.
var x = new Array(10); for (var i = 0; i < x.length; i++) { x[i] = new Array(3); } console.log(x);
- 6 Can they use things like strings for their keys and values? myArray['Book']['item1'] ? – Diego Commented Jun 8, 2009 at 19:54
- 46 @Diego, yes, but that's not what arrays are intended for. It's better to use an object when your keys are strings. – Matthew Crumley Commented Jun 8, 2009 at 20:05
- 10 I like this example better than the accepted answer because this can be implemented for dynamically sized arrays, e.g. new Array(size) where size is a variable. – Variadicism Commented Sep 12, 2015 at 22:44
- 1 This is working, thanks. You can see the example Gargo jsfiddle.net/matasoy/oetw73sj – matasoy Commented Sep 23, 2016 at 7:23
- Doesn't work at all!! new Array?? in which language? running the snippet you get only undefined! – Giox Commented May 21, 2020 at 22:15
Similar to activa's answer, here's a function to create an n-dimensional array:
- 2 Can this create a 4 dimensional array? – trusktr Commented May 19, 2011 at 2:18
- 4 @trusktr: Yes, you could create as many dimensions as you want (within your memory constraints). Just pass in the length of the four dimensions. For example, var array = createArray(2, 3, 4, 5); . – Matthew Crumley Commented May 19, 2011 at 4:21
- 4 Best answer ! However, I would not recommend to use it with 0 or 1 parameters (useless) – Apolo Commented May 15, 2014 at 14:11
- 2 @BritishDeveloper Yes. This is a 5D array with each length at 5: [[[[[null,null],[null,null]],[[null,null],[null,null]]],[[[null,null],[null,null]],[[null,null],[null,null]]]],[[[[null,null],[null,null]],[[null,null],[null,null]]],[[[null,null],[null,null]],[[null,null],[null,null]]]]] – bb216b3acfd8f72cbc8f899d4d6963 Commented May 20, 2019 at 22:25
- 5 @haykam sorry to waste your time - I was being sarcastic :/ – BritishDeveloper Commented Jul 18, 2019 at 22:39
How to create an empty two dimensional array (one-line)
2 and 4 being first and second dimensions respectively.
We are making use of Array.from , which can take an array-like param and an optional mapping for each of the elements.
Array.from(arrayLike[, mapFn[, thisArg]])
var arr = Array.from(Array(2), () => new Array(4)); arr[0][0] = 'foo'; console.info(arr);
The same trick can be used to Create a JavaScript array containing 1...N
Alternatively (but more inefficient 12% with n = 10,000 )
The performance decrease comes with the fact that we have to have the first dimension values initialized to run .map . Remember that Array will not allocate the positions until you order it to through .fill or direct value assignment.
var arr = Array(2).fill(null).map(() => Array(4)); arr[0][0] = 'foo'; console.info(arr);
Here's a method that appears correct, but has issues .
While it does return the apparently desired two dimensional array ( [ [ <4 empty items> ], [ <4 empty items> ] ] ), there a catch: first dimension arrays have been copied by reference. That means a arr[0][0] = 'foo' would actually change two rows instead of one.
var arr = Array(2).fill(Array(4)); arr[0][0] = 'foo'; console.info(arr); console.info(arr[0][0], arr[1][0]);
![javascript array assignment Trent's user avatar](https://i.sstatic.net/Vyvw7.jpg?s=64)
- 3 I suggest this: Array.from({length:5}, () => []) – vsync Commented Aug 29, 2018 at 9:11
- 1 Subjective here but this answer (the first and second within it) seems like the best balance of succinct, fast, and modern. – Brady Dowling Commented Oct 2, 2019 at 21:08
- 2 Best one-liner answer! – Rodrigo Amaral Commented Sep 10, 2020 at 13:22
- 2 what is the difference between Array.from(Array(2), () => new Array(4)) and Array.from(Array(2), () => Array(4)) ? – Owen Young Commented May 24, 2022 at 7:48
- 1 There is a mistake here in that new Array(100).fill(null).map(() => new Array(100).fill(null)) is faster than Array.from({ length: 100 }, () => Array.from({ length: 100 }, () => null)); When testing arrays of all sizes (10 to 1000), Array.from is ~67% slower than new Array see: jsbench.me/z3l905yt6p/2 – AlexManning Commented Oct 8, 2022 at 17:03
Javascript only has 1-dimensional arrays, but you can build arrays of arrays, as others pointed out.
The following function can be used to construct a 2-d array of fixed dimensions:
The number of columns is not really important, because it is not required to specify the size of an array before using it.
Then you can just call:
![javascript array assignment Philippe Leybaert's user avatar](https://i.sstatic.net/woDXH.jpg?s=64)
- i want to make a 2-dim array that would represent a deck of cards. Which would be a 2-dim array that holds the card value and then in then the suit. What would be the easiest way to do that. – Doug Hauf Commented Mar 3, 2014 at 17:58
- 1 function Create2DArray(rows) { var arr = []; for (var i=0;i<rows;i++) { arr[i] = []; } return arr; } function print(deck) { for(t=1;t<=4;t++) { for (i=1;i<=13;i++) { document.writeln(deck[t][i]); } } } fucntion fillDeck(d) { for(t=1;t<=4;t++) { myCardDeck[t][1] = t; for (i=1;i<=13;i++) { myCardDeck[t][i] = i; } } } function loadCardDeck() { var myCardDeck = Create2DArray(13); fillDeck(myCardDeck); print(myCardDeck); } – Doug Hauf Commented Mar 3, 2014 at 17:58
- 2 @Doug: You actually want a one-dimensional array of objects with 2 attributes. var deck= []; deck[0]= { face:1, suit:'H'}; – TeasingDart Commented Sep 18, 2015 at 23:21
- @DougHauf that's a minified 2D-array ?? :P :D – Mahi Commented Nov 9, 2016 at 12:50
The easiest way:
- 31 which is a 2-dimension array – Maurizio In denmark Commented Jul 2, 2013 at 13:07
- 17 Yeah, careful with that. Assigning myArray[0][whatever] is fine, but try and set myArray[1][whatever] and it complains that myArray[1] is undefined. – Philip Commented Apr 17, 2014 at 16:24
- 25 @Philip you have to set myArray[1]=[]; before assigning myArray[1][0]=5; – 182764125216 Commented Sep 19, 2014 at 20:14
- 7 Be aware, this does not "create an empty 1x1 array" as @AndersonGreen wrote. It creates a "1x0" array (i.e. 1 row containing an array with 0 columns). myArray.length == 1 and myArray[0].length == 0 . Which then gives the wrong result if you then copy a "genuinely empty" "0x0" array into it. – JonBrave Commented Nov 17, 2016 at 9:20
- 4 @182764125216 that was knowledge of the day for me. Thanks :) – th3pirat3 Commented Feb 7, 2018 at 23:20
The reason some say that it isn't possible is because a two dimensional array is really just an array of arrays. The other comments here provide perfectly valid methods of creating two dimensional arrays in JavaScript, but the purest point of view would be that you have a one dimensional array of objects, each of those objects would be a one dimensional array consisting of two elements.
So, that's the cause of the conflicting view points.
- 43 No, it's not. In some languages, you can have multidimensional arrays like string[3,5] = "foo"; . It's a better approach for some scenarios, because the Y axis is not actually a child of the X axis. – rafasoares Commented Aug 4, 2011 at 15:29
- 4 Once it gets to the underlying machine code, all tensors of dimension > 1 are arrays of arrays, whichever language we are talking about. It is worthwhile keeping this in mind for reasons of cache optimisation. Any decent language that caters seriously for numerical computing will allow you to align your multidimensional structure in memory such that your most-used dimension is stored contiguously. Python's Numpy, Fortran, and C, come to mind. Indeed there are cases when it is worthwhile to reduce dimensionality into multiple structures for this reason. – Thomas Browne Commented Oct 27, 2014 at 18:18
- Computers have no notion of dimensions. There is only 1 dimension, the memory address. Everything else is notational decoration for the benefit of the programmer. – TeasingDart Commented Sep 18, 2015 at 23:23
- 3 @ThomasBrowne Not exactly. "Arrays of arrays" require some storage for the sizes of inner arrays (they may differ) and another pointer dereferencing to find the place where an inner array is stored. In any "decent" language multidimentional arrays differ from jagged arrays, because they're different data structures per se. (And the confusing part is that C arrays are multidimentional, even though they're indexed with [a][b] syntax.) – polkovnikov.ph Commented Dec 18, 2015 at 23:20
Few people show the use of push: To bring something new, I will show you how to initialize the matrix with some value, example: 0 or an empty string "". Reminding that if you have a 10 elements array, in javascript the last index will be 9!
usage examples:
![javascript array assignment Sergio Abreu's user avatar](https://i.sstatic.net/rgAj1.jpg?s=64)
- I remove last for (which sets default value) from your procedure and write m=matrix(3,4); m[1][2]=2; console.log(JSON.stringify(m)); - and we get very strage matrix (too much nested) - you repair it in last for-defaultValue step, but I think you can rewrite procedure to use less nested arras before setting default values. – Kamil Kiełczewski Commented Jan 21, 2020 at 14:42
- 1 for javascript world, this is the perfect solutions. Thank you very much for providing this solutions – AMIC MING Commented May 6, 2021 at 7:47
- You are so kind AMIC – Sergio Abreu Commented May 7, 2021 at 13:08
It will generate an array a of the length 10, filled with arrays. (Push adds an element to an array and returns the new length)
- 14 One-liner: for (var a=[]; a.push([])<10;); ? – Bergi Commented Jul 7, 2014 at 22:07
- @Bergi will the a variable still be defined in the next line..? – StinkyCat Commented Apr 11, 2016 at 10:48
- 1 @StinkyCat: Yes, that's how var works. It's always function-scoped. – Bergi Commented Apr 11, 2016 at 10:51
- I know, therefore your one-liner is useless in this case: you cannot "access its members" (check question) – StinkyCat Commented Apr 11, 2016 at 11:05
- 1 domenukk and @Bergi, you're both correct. I tried it out and I can access a after the for. I apologize! and thank you, may this be a lesson to me ;) – StinkyCat Commented Apr 13, 2016 at 14:06
The sanest answer seems to be
var nrows = ~~(Math.random() * 10); var ncols = ~~(Math.random() * 10); console.log(`rows:${nrows}`); console.log(`cols:${ncols}`); var matrix = new Array(nrows).fill(0).map(row => new Array(ncols).fill(0)); console.log(matrix);
Note we can't directly fill with the rows since fill uses shallow copy constructor, therefore all rows would share the same memory...here is example which demonstrates how each row would be shared (taken from other answers):
- This should be at the very top. I did something similar using Array.apply(null, Array(nrows)) but this is much more elegant. – dimiguel Commented Mar 25, 2016 at 6:05
- This regard my last comment... Internet Explorer and Opera don't have support for fill . This won't work on a majority of browsers. – dimiguel Commented Mar 25, 2016 at 20:50
- @dimgl Fill can be emulated in this instance with a constant map: Array(nrows).map(() => 0) , or, Array(nrows).map(function(){ return 0; }); – Conor O'Brien Commented Jan 17, 2017 at 18:56
![javascript array assignment Chicharito's user avatar](https://i.sstatic.net/HaFMf.jpg?s=64)
- that's horrible, what if they array is 1000x1000? are you going to write thousands of lines? – Elerium115 Commented Feb 16 at 10:59
Performance
Today 2020.02.05 I perform tests on MacOs HighSierra 10.13.6 on Chrome v79.0, Safari v13.0.4 and Firefox v72.0, for chosen solutions.
Conclusions for non-initialised 2d array
- esoteric solution {}/arr[[i,j]] (N) is fastest for big and small arrays and it looks like it is good choice for big sparse arrays
- solutions based on for-[]/while (A,G) are fast and they are good choice for small arrays.
- solutions for-[] (B,C) are fast and they are good choice for big arrays
- solutions based on Array..map/from/fill (I,J,K,L,M) are quite slow for small arrays, and quite fast for big arrays
- surprinsingly for-Array(n) (B,C) is much slower on safari than for-[] (A)
- surprinsingly for-[] (A) for big array is slow on all browsers
- solutions K is slow for small arrays for all browsers
- solutions A,E,G are slow for big arrays for all browsers
- solution M is slowest for all arrays on all browsers
![javascript array assignment enter image description here](https://i.sstatic.net/YD4S1.png)
Conclusions for initialised 2d array
- solutions based on for/while (A,B,C,D,E,G) are fastest/quite fast for small arrays on all browsers
- solutions based on for (A,B,C,E) are fastest/quite fast for big arrays on all browsers
- solutions based on Array..map/from/fill (I,J,K,L,M) are medium fast or slow for small arrays on all browsers
- solutions F,G,H,I,J,K,L for big arrays are medium or fast on chrome and safari but slowest on firefox.
- esoteric solution {}/arr[[i,j]] (N) is slowest for small and big arrays on all browsers
![javascript array assignment enter image description here](https://i.sstatic.net/y0zh2.png)
Test for solutions which not fill (initialise) output array
We test speed of solutions for
- small arrays (12 elements) - you can perform tests on your machine HERE
- big arrays (1 million elements) arrays - you can perform tests on your machine HERE
function A(r) { var arr = []; for (var i = 0; i < r; i++) arr[i] = []; return arr; } function B(r, c) { var arr = new Array(r); for (var i = 0; i < arr.length; i++) arr[i] = new Array(c); return arr; } function C(r, c) { var arr = Array(r); for (var i = 0; i < arr.length; i++) arr[i] = Array(c); return arr; } function D(r, c) { // strange, but works var arr = []; for (var i = 0; i < r; i++) { arr.push([]); arr[i].push(Array(c)); } return arr; } function E(r, c) { let array = [[]]; for (var x = 0; x < c; x++) { array[x] = []; for (var y = 0; y < r; y++) array[x][y] = [0]; } return array; } function F(r, c) { var makeArray = function(dims, arr) { if (dims[1] === undefined) { return Array(dims[0]); } arr = Array(dims[0]); for (var i = 0; i < dims[0]; i++) { arr[i] = Array(dims[1]); arr[i] = makeArray(dims.slice(1), arr[i]); } return arr; } return makeArray([r, c]); } function G(r) { var a = []; while (a.push([]) < r); return a; } function H(r,c) { function createArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while(i--) arr[length-1 - i] = createArray.apply(this, args); } return arr; } return createArray(r,c); } function I(r, c) { return [...Array(r)].map(x => Array(c)); } function J(r, c) { return Array(r).fill(0).map(() => Array(c)); } function K(r, c) { return Array.from(Array(r), () => Array(c)); } function L(r, c) { return Array.from({length: r}).map(e => Array(c)); } function M(r, c) { return Array.from({length: r}, () => Array.from({length: c}, () => {})); } function N(r, c) { return {} } // ----------------------------------------------- // SHOW // ----------------------------------------------- log = (t, f) => { let A = f(3, 4); // create array with 3 rows and 4 columns A[1][2] = 6 // 2-nd row 3nd column set to 6 console.log(`${t}[1][2]: ${A[1][2]}, full: ${JSON.stringify(A).replace(/null/g,'x')}`); } log2 = (t, f) => { let A = f(3, 4); // create array with 3 rows and 4 columns A[[1,2]] = 6 // 2-nd row 3nd column set to 6 console.log(`${t}[1][2]: ${A[[1,2]]}, full: ${JSON.stringify(A).replace(/null/g,'x')}`); } log('A', A); log('B', B); log('C', C); log('D', D); log('E', E); log('F', F); log('G', G); log('H', H); log('I', I); log('J', J); log('K', K); log('L', L); log('M', M); log2('N', N); This is presentation of solutions - not benchmark
Test for solutions which fill (initialise) output array
function A(r, c, def) { var arr = []; for (var i = 0; i < r; i++) arr[i] = Array(c).fill(def); return arr; } function B(r, c, def) { var arr = new Array(r); for (var i = 0; i < arr.length; i++) arr[i] = new Array(c).fill(def); return arr; } function C(r, c, def) { var arr = Array(r); for (var i = 0; i < arr.length; i++) arr[i] = Array(c).fill(def); return arr; } function D(r, c, def) { // strange, but works var arr = []; for (var i = 0; i < r; i++) { arr.push([]); arr[i].push(Array(c)); } for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[i][j]=def return arr; } function E(r, c, def) { let array = [[]]; for (var x = 0; x < c; x++) { array[x] = []; for (var y = 0; y < r; y++) array[x][y] = def; } return array; } function F(r, c, def) { var makeArray = function(dims, arr) { if (dims[1] === undefined) { return Array(dims[0]).fill(def); } arr = Array(dims[0]); for (var i = 0; i < dims[0]; i++) { arr[i] = Array(dims[1]); arr[i] = makeArray(dims.slice(1), arr[i]); } return arr; } return makeArray([r, c]); } function G(r, c, def) { var a = []; while (a.push(Array(c).fill(def)) < r); return a; } function H(r,c, def) { function createArray(length) { var arr = new Array(length || 0), i = length; if (arguments.length > 1) { var args = Array.prototype.slice.call(arguments, 1); while(i--) arr[length-1 - i] = createArray.apply(this, args).fill(def); } return arr; } return createArray(r,c); } function I(r, c, def) { return [...Array(r)].map(x => Array(c).fill(def)); } function J(r, c, def) { return Array(r).fill(0).map(() => Array(c).fill(def)); } function K(r, c, def) { return Array.from(Array(r), () => Array(c).fill(def)); } function L(r, c, def) { return Array.from({length: r}).map(e => Array(c).fill(def)); } function M(r, c, def) { return Array.from({length: r}, () => Array.from({length: c}, () => def)); } function N(r, c, def) { let arr={}; for (var i = 0; i < r; i++) for (var j = 0; j < c; j++) arr[[i,j]]=def; return arr; } // ----------------------------------------------- // SHOW // ----------------------------------------------- log = (t, f) => { let A = f(1000,1000,7); // create array with 1000 rows and 1000 columns, // each array cell initilised by 7 A[800][900] = 5 // 800nd row and 901nd column set to 5 console.log(`${t}[1][2]: ${A[1][2]}, ${t}[800][901]: ${A[800][900]}`); } log2 = (t, f) => { let A = f(1000,1000,7); // create array with 1000 rows and 1000 columns, // each array cell initilised by 7 A[[800,900]] = 5 // 800nd row 900nd column set to 5 console.log(`${t}[1][2]: ${A[[1,2]]}, ${t}[800][900]: ${A[[800,900]]}`); } log('A', A); log('B', B); log('C', C); log('D', D); log('E', E); log('F', F); log('G', G); log('H', H); log('I', I); log('J', J); log('K', K); log('L', L); log('M', M); log2('N', N); This is presentation of solutions - not benchmark
![javascript array assignment enter image description here](https://i.sstatic.net/oBoCA.png)
To create an 4x6 array, simply do this
It's usually a good practice to start with an empty array, rather than filling w random values. (You normally declare array as const x = [] in 1D, so better to start w empty in 2D.)
This is what i achieved :
var appVar = [[]]; appVar[0][4] = "bineesh"; appVar[0][5] = "kumar"; console.log(appVar[0][4] + appVar[0][5]); console.log(appVar);
This spelled me bineeshkumar
- 3 Notice how you can only access the 0 index of the parent array. This isn't as useful as something which allows you to set, for example, appVar[5][9] = 10; ... you would get 'Unable to set property "9" of undefined' with this. – RaisinBranCrunch Commented Jul 30, 2017 at 16:38
- But appVar[1][4] = "bineesh"; is wrong, how to solve it? – Gank Commented May 20, 2018 at 13:50
- 1 @RaisinBran and @Gank This creates only one row with dynamic multiple columns. If you want to have multiple rows, you can do something like this: var appVar = [[], [], [], [], [], []]; This will create 6 rows with each dynamic multiple columns. – Abdulwehab Commented Aug 9, 2022 at 8:29
Two dimensional arrays are created the same way single dimensional arrays are. And you access them like array[0][1] .
![javascript array assignment TJ L's user avatar](https://i.sstatic.net/0dc9Z.jpg?s=64)
For one liner lovers Array.from()
Another one (from comment by dmitry_romanov) use Array().fill()
Using ES6+ spread operator ("inspired" by InspiredJW answer :) )
- 3 we can remove 0 in the first fill() function: const arr2d = Array(8).fill().map(() => Array(8).fill("0")); – Jinsong Li Commented Nov 21, 2017 at 14:38
I'm not sure if anyone has answered this but I found this worked for me pretty well -
For a 2 dimensional array, for instance.
- How can I do this dynamically? I want the inner arrays with different sizes. – alap Commented Jan 19, 2014 at 16:48
- 3 You don't need extra commas var array = [[],[]] is adequate. – Kaya Toast Commented Jan 31, 2015 at 7:29
To create a non-sparse "2D" array (x,y) with all indices addressable and values set to null:
bonus "3D" Array (x,y,z)
Variations and corrections on this have been mentioned in comments and at various points in response to this question but not as an actual answer so I am adding it here.
It should be noted that (similar to most other answers) this has O(x*y) time complexity so it probably not suitable for very large arrays.
- 1 be careful because fill set the same value. if change null to `object it will be the same object in every column – Stanislav Mayorov Commented Mar 14, 2019 at 13:08
- @StanislavMayorov If you want to set each cell's value, just use the same trick: let 2Darray = new Array(x).fill(null).map(item =>(new Array(y).fill(null).map(cell =>(yourValueHere)))) – bb216b3acfd8f72cbc8f899d4d6963 Commented May 20, 2019 at 22:22
To create a 2D array in javaScript we can create an Array first and then add Arrays as it's elements. This method will return a 2D array with the given number of rows and columns.
to create an Array use this method as below.
- 2 Please would you add some explanatory information to your ansdwer showing how it works, and why it solves the problem. This will help others who find this page in the future – Our Man in Bananas Commented Jun 25, 2014 at 12:16
- When would you need an Array that is preinitialized with a certain number of colums in Javascript? You can access the n-th element of a [] array as well. – domenukk Commented Jul 8, 2014 at 14:49
- I noticed the function starts with capital C, which (by certain conventions) suggest it would be a Function constructor and you would use it with the new keyword. A very minor and somewhat opinionated maybe, but I would still suggest un-capitalized word. – Hachi Commented Aug 24, 2014 at 5:53
Use Array Comprehensions
In JavaScript 1.7 and higher you can use array comprehensions to create two dimensional arrays. You can also filter and/or manipulate the entries while filling the array and don't have to use loops.
You can create any n x m array you want and fill it with a default value by calling
More examples and documentation can be found here .
Please note that this is not a standard feature yet .
- A quick google check here... yup... the for statement is still a loop... – Pimp Trizkit Commented Mar 10, 2018 at 15:25
- 1 It is not supported by any browser - HERE ? – Kamil Kiełczewski Commented Jan 21, 2020 at 14:56
Row and Column sizes of an array known only at the run time then following method could be used for creating a dynamic 2d array .
var num = '123456'; var row = 3; // Known at run time var col = 2; // Known at run time var i = 0; var array2D = [[]]; for(var r = 0; r < row; ++r) { array2D[r] = []; for(var c = 0; c < col; ++c) { array2D[r][c] = num[i++]; } } console.log(array2D); // [[ '1', '2' ], // [ '3', '4' ], // [ '5', '6' ]] console.log(array2D[2][1]); // 6
- Works well, but shouldn't col and row be swapped? Your visual representation seems to go against the convention of rows being horizontal, and columns being vertical. – Chewie The Chorkie Commented Feb 23, 2021 at 0:54
You can create a 2 Dimensional array m x n with initial value m and n can be any numbers v can be any value string , number , undefined .
One approach can be var a = [m][n]
![javascript array assignment Alex's user avatar](https://lh4.googleusercontent.com/-Tha5CBoNViQ/AAAAAAAAAAI/AAAAAAAAAAA/ACHi3rcQZ6h-DhXh_9kGlJ2_KfAE63a0KQ/mo/photo.jpg?sz=64)
- I like your answer, but you don't need to use map(), you can do it with fill() alone, like this: var map = new Array(height).fill(new Array(width).fill(val)); creating an array like so: map[y][x] = val; – Tornseglare Commented Dec 9, 2020 at 17:07
The following example defines a two-dimensional array named activities:
In the activities array, the first dimension represents the activity and the second one shows the number of hours spent per day for each.
To show the activities array in the console, you use the console.table() method as follows:
The following illustrates the output:
┌─────────┬─────────────┬───┐ │ (index) │ 0 │ 1 │ ├─────────┼─────────────┼───┤ │ 0 │ 'Work' │ 9 │ │ 1 │ 'Eat' │ 1 │ │ 2 │ 'Commute' │ 2 │ │ 3 │ 'Play Game' │ 1 │ │ 4 │ 'Sleep' │ 7 │ └─────────┴─────────────┴───┘
Note that the (index) column is for the illustration that indicates the indices of the inner array.
To access an element of the multidimensional array, you first use square brackets to access an element of the outer array that returns an inner array; and then use another square bracket to access the element of the inner array.
The following example returns the second element of the first inner array in the activities array above:
Adding elements to the JavaScript multidimensional array
You can use the Array methods such as push() and splice() to manipulate elements of a multidimensional array.
For example, to add a new element at the end of the multidimensional array, you use the push() method as follows:
┌─────────┬─────────────┬───┐ │ (index) │ 0 │ 1 │ ├─────────┼─────────────┼───┤ │ 0 │ 'Work' │ 9 │ │ 1 │ 'Eat' │ 1 │ │ 2 │ 'Commute' │ 2 │ │ 3 │ 'Play Game' │ 1 │ │ 4 │ 'Sleep' │ 7 │ │ 5 │ 'Study' │ 2 │ └─────────┴─────────────┴───┘
To insert an element in the middle of the array, you use the splice() method. The following inserts an element in the second position of the activities array:
┌─────────┬───────────────┬───┐ │ (index) │ 0 │ 1 │ ├─────────┼───────────────┼───┤ │ 0 │ 'Work' │ 9 │ │ 1 │ 'Programming' │ 2 │ │ 2 │ 'Eat' │ 1 │ │ 3 │ 'Commute' │ 2 │ │ 4 │ 'Play Game' │ 1 │ │ 5 │ 'Sleep' │ 7 │ │ 6 │ 'Study' │ 2 │ └─────────┴───────────────┴───┘
This example calculates the percentage of the hours spent on each activity and appends the percentage to the inner array.
┌─────────┬───────────────┬───┬───────┐ │ (index) │ 0 │ 1 │ 2 │ ├─────────┼───────────────┼───┼───────┤ │ 0 │ 'Work' │ 9 │ '38%' │ │ 1 │ 'Programming' │ 2 │ '8%' │ │ 2 │ 'Eat' │ 1 │ '4%' │ │ 3 │ 'Commute' │ 2 │ '8%' │ │ 4 │ 'Play Game' │ 1 │ '4%' │ │ 5 │ 'Sleep' │ 7 │ '29%' │ │ 6 │ 'Study' │ 2 │ '8%' │ └─────────┴───────────────┴───┴───────┘
Removing elements from the JavaScript multidimensional array
To remove an element from an array, you use the pop() or splice() method.
For example, the following statement removes the last element of the activities array:
┌─────────┬───────────────┬───┬───────┐ │ (index) │ 0 │ 1 │ 2 │ ├─────────┼───────────────┼───┼───────┤ │ 0 │ 'Work' │ 9 │ '38%' │ │ 1 │ 'Programming' │ 2 │ '8%' │ │ 2 │ 'Eat' │ 1 │ '4%' │ │ 3 │ 'Commute' │ 2 │ '8%' │ │ 4 │ 'Play Game' │ 1 │ '4%' │ │ 5 │ 'Sleep' │ 7 │ '29%' │ └─────────┴───────────────┴───┴───────┘
Similarly, you can remove the elements from the inner array of the multidimensional array by using the pop() method. The following example removes the percentage element from the inner arrays of the activities array.
┌─────────┬───────────────┬───┐ │ (index) │ 0 │ 1 │ ├─────────┼───────────────┼───┤ │ 0 │ 'Work' │ 9 │ │ 1 │ 'Programming' │ 2 │ │ 2 │ 'Eat' │ 1 │ │ 3 │ 'Commute' │ 2 │ │ 4 │ 'Play Game' │ 1 │ │ 5 │ 'Sleep' │ 7 │ └─────────┴───────────────┴───┘
Iterating over elements of the JavaScript multidimensional array
To iterate a multidimensional array, you use a nested for loop as in the following example.
The first loop iterates over the elements of the outer array and the nested loop iterates over elements of the inner array.
The following shows the output of the script in the console:
[0,0] = Work [0,1] = 9 [1,0] = Eat [1,1] = 1 [2,0] = Commute [2,1] = 2 [3,0] = Play Game [3,1] = 1 [4,0] = Sleep [4,1] = 7 [5,0] = Study [5,1] = 2
Or you can use the forEach() method twice:
Work 9 Eat 1 Commute 2 Play Game 1 Sleep 7 Study 2
![javascript array assignment PJProudhon's user avatar](https://i.sstatic.net/IuMvI.png?s=64)
- 3 Shameless copy & paste from javascripttutorial.net/javascript-multidimensional-array – Mario Werner Commented Dec 22, 2021 at 12:56
My approach is very similar to @Bineesh answer but with a more general approach.
You can declare the double array as follows:
And the storing and accessing the contents in the following manner:
This will print the expected output
I found below is the simplest way:
var array1 = [[]]; array1[0][100] = 5; alert(array1[0][100]); alert(array1.length); alert(array1[0].length);
- array1[1][100] = 666; throws Uncaught TypeError: Cannot set property '100' of undefined – Kamil Kiełczewski Commented Jan 21, 2020 at 14:35
- @KamilKiełczewski you are right, looks like this only initiate for the first array of array, for the second before you do array1[1][100] = 666; , you need to do this array1[1] = []; . – Sam YC Commented Jan 22, 2020 at 1:22
var playList = [ ['I Did It My Way', 'Frank Sinatra'], ['Respect', 'Aretha Franklin'], ['Imagine', 'John Lennon'], ['Born to Run', 'Bruce Springsteen'], ['Louie Louie', 'The Kingsmen'], ['Maybellene', 'Chuck Berry'] ]; function print(message) { document.write(message); } function printSongs( songs ) { var listHTML; listHTML = '<ol>'; for ( var i = 0; i < songs.length; i += 1) { listHTML += '<li>' + songs[i][0] + ' by ' + songs[i][1] + '</li>'; } listHTML += '</ol>'; print(listHTML); } printSongs(playList);
![javascript array assignment antelove's user avatar](https://i.sstatic.net/pvdwf.jpg?s=64)
Below one, creates a 5x5 matrix and fill them with null
var md = []; for(var i=0; i<5; i++) { md.push(new Array(5).fill(null)); } console.log(md);
![javascript array assignment Sivakumar Tadisetti's user avatar](https://i.sstatic.net/RMZOu.jpg?s=64)
- 3 This answer is wrong. It will create an array with same array filling in its slots. md[1][0] = 3 and all the rest of elements are updated too – Qiang Commented Nov 15, 2016 at 6:33
ES6+, ES2015+ can do this in even simpler way
Creating 3 x 2 Array filled with true
- I need to confess. I "adopted" your answer and added to mine , the one-liners collection. – my- Commented Jan 24, 2020 at 21:06
I had to make a flexible array function to add "records" to it as i needed and to be able to update them and do whatever calculations e needed before i sent it to a database for further processing. Here's the code, hope it helps :).
Feel free to optimize and / or point out any bugs :)
![javascript array assignment CJ Mendes's user avatar](https://i.sstatic.net/Cxk3Y.png?s=64)
- How about just aLine.push([clmn1, clmn2, clmn3]); ? – Pimp Trizkit Commented Mar 10, 2018 at 15:55
Javascript does not support two dimensional arrays, instead we store an array inside another array and fetch the data from that array depending on what position of that array you want to access. Remember array numeration starts at ZERO .
Code Example:
Not the answer you're looking for? Browse other questions tagged javascript arrays multidimensional-array or ask your own question .
- The Overflow Blog
- Battling ticket bots and untangling taxes at the frontiers of e-commerce
- Ryan Dahl explains why Deno had to evolve with version 2.0
- Featured on Meta
- We've made changes to our Terms of Service & Privacy Policy - July 2024
- Bringing clarity to status tag usage on meta sites
- Feedback requested: How do you use tag hover descriptions for curating and do...
Hot Network Questions
- Handling Race Condition with Concurrent SOQL Queries in Salesforce Integration
- The meaning of “manage” in this context
- Is there a way to swap my longbow from being a ranger for a shortbow?
- Inequality between archimedean and non-archimedean height function on number fields
- How do I delete a systemd transient service like one created by systemd-run?
- Multiple unds in a sentence
- For applying to a STEM research position at a U.S. research university, should a resume include a photo?
- Is "UN law" a thing?
- Rounding vertices of polygon to fixed number of decimal places in QGIS
- Find all pairs of positive compatible numbers less than 100 by proof
- Is this misleading "convenience fee" legal?
- How to remove a file named "."?
- Would weightlessness (i.e. in thrill rides, planes, skydiving, etc.) be different on a Flat Earth?
- What might cause these striations in this solder joint?
- Homotopy groups of the space of diffeomorphisms
- Is sudoku only one puzzle?
- Rearrange these numbers and symbols to make a true equation
- How many people could we get off of the planet in a month?
- How soon to fire rude and chaotic PhD student?
- Are ~渋る and ~惜しむ any different as verbal suffixes?
- Are the 'weak' in Joel 3:10 who are to say "I am strong", the people of Judah and Jerusalem - or are they people of the nations whom God will judge?
- Is there a good explanation for the existence of the C19 globular cluster with its very low metallicity?
- Why are swimming goggles typically made from a different material than diving masks?
- Can data be preprocessed when using EdDSA with SHAKE?
![](http://sektorel.online/777/templates/cheerup/res/banner1.gif)
IMAGES
COMMENTS
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. ... The rest property of array destructuring assignment can be another array or object binding pattern. The inner destructuring destructures from the array created after ...
Creating an Array. Using an array literal is the easiest way to create a JavaScript Array. Syntax: const array_name = [ item1, item2, ... ]; It is a common practice to declare arrays with the const keyword. Learn more about const with arrays in the chapter: JS Array Const.
JavaScript arrays are zero-indexed: the first element of an array is at index 0, ... Finally, it's important to understand that assigning an existing array to a new variable doesn't create a copy of either the array or its elements. Instead the new variable is just a reference, ...
Here is an example of an array with four elements: type Number, Boolean, String, and Object. const mixedTypedArray = [100, true, 'freeCodeCamp', {}]; The position of an element in the array is known as its index. In JavaScript, the array index starts with 0, and it increases by one with each element.
The destructuring assignment syntax unpack object properties into variables: let {firstName, lastName} = person; It can also unpack arrays and any other iterables: let [firstName, lastName] = person;
It's called "destructuring assignment," because it "destructurizes" by copying items into variables. However, the array itself is not modified. It's just a shorter way to write: // let [firstName, surname] = arr; let firstName = arr [0]; let surname = arr [1]; Ignore elements using commas.
The destructuring assignment is a cool feature that came along with ES6. Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables. Why
If the value taken from the array is undefined, you can assign the variable a default value, like this: let a, b; [a = 1, b = 2] = [10]; console.log(a); // 10 console.log(b); // 2 Code language: JavaScript (javascript) If the getItems() function doesn't return an array and you expect an array, the destructing assignment will result in an ...
Javascript assigning multiple arrays. 1. Javascript: Array declaration - derived from textbook studies. 2. Javascript - Array Assignment. 2. Array as a Variable Assignment in Javascript. 0. Declaration of arrays. Hot Network Questions Function to find the most common numeric ordered pairings (value, count)
Working with JavaScript arrays and objects can be more fun if you destructure them. This helps when you're fetching stored data. In this article, you will learn how you can take destructuring to the next level in JavaScript arrays and objects. ... Assigning a variable name will always help us keep our code clean, especially when it comes to ...
JavaScript Arrays: Create, Access, Add & Remove Elements. We have learned that a variable can hold only one value. We cannot assign multiple values to a single variable. JavaScript array is a special type of variable, which can store multiple values using a special syntax. The following declares an array with five numeric values.
In JavaScript, arrays are a type of object. However, Arrays use numbered indexes to access elements. Objects use named indexes (keys) to access values. Since arrays are objects, the array elements are stored by reference. Hence, when we assign an array to another variable, we are just pointing to the same array in memory.
Arrays can be created using a constructor with a single number parameter. An array is created with its length property set to that number, and the array elements are empty slots. js. const arrayEmpty = new Array(2); console.log(arrayEmpty.length); // 2. console.log(arrayEmpty[0]); // undefined; actually, it is an empty slot.
Destructuring Assignment in JavaScript. Destructuring Assignment is a JavaScript expression that allows to unpack of values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, and nested objects, and assigned to variables. In Destructuring Assignment on the left-hand side, we define which ...
Use the correct assignment operator that will result in x being 15 (same as x = x + y ). Start the Exercise. Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, Python, PHP, Bootstrap, Java, XML and more.
If you need to remove one or more elements from a specific position of an array, you can use the splice() method. The first parameter of splice() is the starting index, while the second is the number of items to remove from the array. So .splice(1, 3) means "start at index = 1 and remove 3 elements".
The assignment operator is completely different from the equals (=) sign used as syntactic separators in other locations, which include:Initializers of var, let, and const declarations; Default values of destructuring; Default parameters; Initializers of class fields; All these places accept an assignment expression on the right-hand side of the =, so if you have multiple equals signs chained ...
The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor function. This approach allows for dynamic initialization and can be used to create arrays with a specified length or elements. Syntax: let arrayName = new Array(); Example: javascript.
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. Here is an example. You can try like this. let a, b, rest; [a, b] = [10, 20]; console.log(a); // expected output: 10. console.log(b); // expected output: 20.
In JavaScript, an array is a variable that is used to store different data types. It basically stores different elements in one box and can be later assesssed with the variable. Declaring an array: let myBox = []; // Initial Array declaration in JS. Arrays can contain multiple data types. let myBox = ['hello', 1, 2, 3, true, 'hi']; Arrays can ...
Logical assignment (38%) is another newer language feature that allows setting variables based on a unary logical operation. Other interesting items include Hashbang grammar (35%) and array.with ...
13. To create a 2D array in javaScript we can create an Array first and then add Arrays as it's elements. This method will return a 2D array with the given number of rows and columns. function Create2DArray(rows,columns) {. var x = new Array(rows); for (var i = 0; i < rows; i++) {.