How to Use Array and Object Destructuring in JavaScript

How to Use Array and Object Destructuring in JavaScript

By Sarah Chima Atuonwu

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 is this necessary?

Imagine we want extract data from an array. Previously, how would this be done?

We can see that when we want to extract data from an array, we have to do the same thing over and over again.

The ES6 destucturing assignment makes it easier to extract this data. How is this so? First, we will discuss the destructuring assignment with arrays. Then we will move on to object destructuring.

Let's get started.

Basic Array Destructuring

If we want to extract data from arrays, it's quite simple using the destructuring assignment.

Let's refer to our first example for arrays. Instead of going through that repetitive process, we'd do this:

We can also do this with the same result.

Declaring Variables before Assignment

Variables can be declared before being assigned like this:

Notice that the variables are set from left to right. So the first variable gets the first item in the array, the second variable gets the second item in the array, and so on.

Skipping Items in an Array

What if we want to get the first and last item on our array instead of the first and second item, and we want to assign only two variables? This can also be done. Look at the example below:

What just happened?

Look at the array on the left side of the variable assignment. Notice that instead of having just one comma, we have three. The comma separator is used to skip values in an array. So if you want to skip an item in an array, just use a comma.

Let's do another one. Let's skip the first and third item on the list. How would we do this?

So the comma separator does the magic. So if we want to skip all items, we just do this:

Assigning the rest of an array

What if we want to assign some of the array to variables and the rest of the items in an array to a particular variable? In that case, we would do this:

Using this pattern, you can unpack and assign the remaining part of an array to a variable.

Destructuring Assignment with Functions

We can also extract data from an array returned from a function. Let's say we have a function that returns an array like the example below:

We get the same results.

Using Default Values

Default values can be assigned to the variables just in case the value extracted from the array is undefined :

So name falls back to "Sarah" because it is not defined in the array.

Swapping Values using the Destructuring Assignment

One more thing. We can use the destructuring assignment to swap the values of variables:

Next, let's move on to Object Destructuring.

Object Destructuring

First, let's see why there is a need for object destructuring.

Say we want to extract data from an object and assign to new variables. Prior to ES6, how would this be done?

See how tedious it is to extract all the data. We have to repeatedly do the same thing. ES6 destructuring really saves the day. Let's jump right into it.

Basic Object Destructuring

Let's repeat the above example with ES6. Instead of assigning values one by one, we can use the object on the left to extract the data:

You'll get the same results. It is also valid to assign variables to an object that haven't been declared:

Variables declared before being assigned

Variables in objects can be declared before being assigned with destructuring. Let's try that:

Wait, what just happened?! Oh, we forgot to add () before the curly brackets.

The ( ) around the assignment statement is required syntax when using the object literal destructuring assignment without a declaration. This is because the {} on the left hand side is considered a block and not an object literal. So here's how to do this the right way:

It is also important to note that when using this syntax, the () should be preceded by a semicolon. Otherwise it might be used to execute a function from the previous line.

Note that the variables in the object on the left hand side should have the same name as a property key in the object person . If the names are different, we'll get undefined :

But if we want to use a new variable name, well, we can.

Using a new Variable Name

If we want to assign values of an object to a new variable instead of using the name of the property, we can do this:

So the values extracted are passed to the new variables foo and bar .

Default values can also be used in object destructuring, just in case a variable is undefined in an object it wants to extract data from:

So if the value is not undefined, the variable stores the value extracted from the object as in the case of name . Otherwise, it used the default value as it did for friend .

We can also set default values when we assign values to a new variable:

So name was extracted from person and assigned to a different variable. friend , on the other hand, was undefined in person , so the new variable bar was assigned the default value.

Computed Property Name

Computed property name is another object literal feature that also works for destructuring. You can specify the name of a property via an expression if you put it in square brackets:

Combining Arrays with Objects

Arrays can also be used with objects in object destructuring:

Nesting in Object Destructuring

Objects can also be nested when destructuring:

Rest in Object Destructuring

The rest syntax can also be used to pick up property keys that are not already picked up by the destructuring pattern. Those keys and their values are copied into a new object:

Here, the remaining properties whose keys where not part of the variable names listed were assigned to the variable others . The rest syntax here is ...others . others can be renamed to whatever variable you want.

One last thing – let's see how Object Destructing can be used in functions.

Object Destructuring and Functions

Object Destructuring can be used to assign parameters to functions:

Notice the {} on the right hand side of the parameters object. It makes it possible for us to call the function without passing any arguments. That is why we got undefined . If we remove it, we'll get an error message.

We can also assign default values to the parameters:

We can do a whole lot of things with Array and Object Destructuring as we have seen in the examples above.

Thank you for reading. :)

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

The Java Tutorials have been written for JDK 8. Examples and practices described in this page don't take advantage of improvements introduced in later releases and might use technology no longer available. See Java Language Changes for a summary of updated language features in Java SE 9 and subsequent releases. See JDK Release Notes for information about new features, enhancements, and removed or deprecated options for all JDK releases.

An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application. This section discusses arrays in greater detail.

An array of 10 elements.

Each item in an array is called an element , and each element is accessed by its numerical index . As shown in the preceding illustration, numbering begins with 0. The 9th element, for example, would therefore be accessed at index 8.

The following program, ArrayDemo , creates an array of integers, puts some values in the array, and prints each value to standard output.

The output from this program is:

In a real-world programming situation, you would probably use one of the supported looping constructs to iterate through each element of the array, rather than write each line individually as in the preceding example. However, the example clearly illustrates the array syntax. You will learn about the various looping constructs ( for , while , and do-while ) in the Control Flow section.

Declaring a Variable to Refer to an Array

The preceding program declares an array (named anArray ) with the following line of code:

Like declarations for variables of other types, an array declaration has two components: the array's type and the array's name. An array's type is written as type [] , where type is the data type of the contained elements; the brackets are special symbols indicating that this variable holds an array. The size of the array is not part of its type (which is why the brackets are empty). An array's name can be anything you want, provided that it follows the rules and conventions as previously discussed in the naming section. As with variables of other types, the declaration does not actually create an array; it simply tells the compiler that this variable will hold an array of the specified type.

Similarly, you can declare arrays of other types:

You can also place the brackets after the array's name:

However, convention discourages this form; the brackets identify the array type and should appear with the type designation.

Creating, Initializing, and Accessing an Array

One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for 10 integer elements and assigns the array to the anArray variable.

If this statement is missing, then the compiler prints an error like the following, and compilation fails:

The next few lines assign values to each element of the array:

Each array element is accessed by its numerical index:

Alternatively, you can use the shortcut syntax to create and initialize an array:

Here the length of the array is determined by the number of values provided between braces and separated by commas.

You can also declare an array of arrays (also known as a multidimensional array) by using two or more sets of brackets, such as String[][] names . Each element, therefore, must be accessed by a corresponding number of index values.

In the Java programming language, a multidimensional array is an array whose components are themselves arrays. This is unlike arrays in C or Fortran. A consequence of this is that the rows are allowed to vary in length, as shown in the following MultiDimArrayDemo program:

Finally, you can use the built-in length property to determine the size of any array. The following code prints the array's size to standard output:

Copying Arrays

The System class has an arraycopy method that you can use to efficiently copy data from one array into another:

The two Object arguments specify the array to copy from and the array to copy to . The three int arguments specify the starting position in the source array, the starting position in the destination array, and the number of array elements to copy.

The following program, ArrayCopyDemo , declares an array of String elements. It uses the System.arraycopy method to copy a subsequence of array components into a second array:

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.

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
  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015 .

  • See full compatibility
  • Report feedback

The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name , and has members for performing common array operations .

Description

In JavaScript, arrays aren't primitives but are instead Array objects with the following core characteristics:

  • JavaScript arrays are resizable and can contain a mix of different data types . (When those characteristics are undesirable, use typed arrays instead.)
  • JavaScript arrays are not associative arrays and so, array elements cannot be accessed using arbitrary strings as indexes, but must be accessed using nonnegative integers (or their respective string form) as indexes.
  • JavaScript arrays are zero-indexed : the first element of an array is at index 0 , the second is at index 1 , and so on — and the last element is at the value of the array's length property minus 1 .
  • JavaScript array-copy operations create shallow copies . (All standard built-in copy operations with any JavaScript objects create shallow copies, rather than deep copies ).

Array indices

Array objects cannot use arbitrary strings as element indexes (as in an associative array ) but must use nonnegative integers (or their respective string form). Setting or accessing via non-integers will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection . The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.

Array elements are object properties in the same way that toString is a property (to be specific, however, toString() is a method). Nevertheless, trying to access an element of an array as follows throws a syntax error because the property name is not valid:

JavaScript syntax requires properties beginning with a digit to be accessed using bracket notation instead of dot notation . It's also possible to quote the array indices (e.g., years['2'] instead of years[2] ), although usually not necessary.

The 2 in years[2] is coerced into a string by the JavaScript engine through an implicit toString conversion. As a result, '2' and '02' would refer to two different slots on the years object, and the following example could be true :

Only years['2'] is an actual array index. years['02'] is an arbitrary string property that will not be visited in array iteration.

Relationship between length and numerical properties

A JavaScript array's length property and numerical properties are connected.

Several of the built-in array methods (e.g., join() , slice() , indexOf() , etc.) take into account the value of an array's length property when they're called.

Other methods (e.g., push() , splice() , etc.) also result in updates to an array's length property.

When setting a property on a JavaScript array when the property is a valid array index and that index is outside the current bounds of the array, the engine will update the array's length property accordingly:

Increasing the length extends the array by adding empty slots without creating any new elements — not even undefined .

Decreasing the length property does, however, delete elements.

This is explained further on the length page.

Array methods and empty slots

Array methods have different behaviors when encountering empty slots in sparse arrays . In general, older methods (e.g. forEach ) treat empty slots differently from indices that contain undefined .

Methods that have special treatment for empty slots include the following: concat() , copyWithin() , every() , filter() , flat() , flatMap() , forEach() , indexOf() , lastIndexOf() , map() , reduce() , reduceRight() , reverse() , slice() , some() , sort() , and splice() . Iteration methods such as forEach don't visit empty slots at all. Other methods, such as concat , copyWithin , etc., preserve empty slots when doing the copying, so in the end the array is still sparse.

Newer methods (e.g. keys ) do not treat empty slots specially and treat them as if they contain undefined . Methods that conflate empty slots with undefined elements include the following: entries() , fill() , find() , findIndex() , findLast() , findLastIndex() , includes() , join() , keys() , toLocaleString() , toReversed() , toSorted() , toSpliced() , values() , and with() .

Copying methods and mutating methods

Some methods do not mutate the existing array that the method was called on, but instead return a new array. They do so by first constructing a new array and then populating it with elements. The copy always happens shallowly — the method never copies anything beyond the initially created array. Elements of the original array(s) are copied into the new array as follows:

  • Objects: the object reference is copied into the new array. Both the original and new array refer to the same object. That is, if a referenced object is modified, the changes are visible to both the new and original arrays.
  • Primitive types such as strings, numbers and booleans (not String , Number , and Boolean objects): their values are copied into the new array.

Other methods mutate the array that the method was called on, in which case their return value differs depending on the method: sometimes a reference to the same array, sometimes the length of the new array.

The following methods create new arrays by accessing this.constructor[Symbol.species] to determine the constructor to use: concat() , filter() , flat() , flatMap() , map() , slice() , and splice() (to construct the array of removed elements that's returned).

The following methods always create new arrays with the Array base constructor: toReversed() , toSorted() , toSpliced() , and with() .

The following table lists the methods that mutate the original array, and the corresponding non-mutating alternative:

Mutating method Non-mutating alternative
No one-method alternative
No one-method alternative

An easy way to change a mutating method into a non-mutating alternative is to use the spread syntax or slice() to create a copy first:

Iterative methods

Many array methods take a callback function as an argument. The callback function is called sequentially and at most once for each element in the array, and the return value of the callback function is used to determine the return value of the method. They all share the same signature:

Where callbackFn takes three arguments:

The current element being processed in the array.

The index of the current element being processed in the array.

The array that the method was called upon.

What callbackFn is expected to return depends on the array method that was called.

The thisArg argument (defaults to undefined ) will be used as the this value when calling callbackFn . The this value ultimately observable by callbackFn is determined according to the usual rules : if callbackFn is non-strict , primitive this values are wrapped into objects, and undefined / null is substituted with globalThis . The thisArg argument is irrelevant for any callbackFn defined with an arrow function , as arrow functions don't have their own this binding .

The array argument passed to callbackFn is most useful if you want to read another index during iteration, because you may not always have an existing variable that refers to the current array. You should generally not mutate the array during iteration (see mutating initial array in iterative methods ), but you can also use this argument to do so. The array argument is not the array that is being built, in the case of methods like map() , filter() , and flatMap() — there is no way to access the array being built from the callback function.

All iterative methods are copying and generic , although they behave differently with empty slots .

The following methods are iterative: every() , filter() , find() , findIndex() , findLast() , findLastIndex() , flatMap() , forEach() , map() , and some() .

In particular, every() , find() , findIndex() , findLast() , findLastIndex() , and some() do not always invoke callbackFn on every element — they stop iteration as soon as the return value is determined.

The reduce() and reduceRight() methods also take a callback function and run it at most once for each element in the array, but they have slightly different signatures from typical iterative methods (for example, they don't accept thisArg ).

The sort() method also takes a callback function, but it is not an iterative method. It mutates the array in-place, doesn't accept thisArg , and may invoke the callback multiple times on an index.

Iterative methods iterate the array like the following (with a lot of technical details omitted):

Note the following:

  • Not all methods do the i in this test. The find , findIndex , findLast , and findLastIndex methods do not, but other methods do.
  • The length is memorized before the loop starts. This affects how insertions and deletions during iteration are handled (see mutating initial array in iterative methods ).
  • The method doesn't memorize the array contents, so if any index is modified during iteration, the new value might be observed.
  • The code above iterates the array in ascending order of index. Some methods iterate in descending order of index ( for (let i = length - 1; i >= 0; i--) ): reduceRight() , findLast() , and findLastIndex() .
  • reduce and reduceRight have slightly different signatures and do not always start at the first/last element.

Generic array methods

Array methods are always generic — they don't access any internal data of the array object. They only access the array elements through the length property and the indexed elements. This means that they can be called on array-like objects as well.

Normalization of the length property

The length property is converted to an integer and then clamped to the range between 0 and 2 53 - 1. NaN becomes 0 , so even when length is not present or is undefined , it behaves as if it has value 0 .

The language avoids setting length to an unsafe integer . All built-in methods will throw a TypeError if length will be set to a number greater than 2 53 - 1. However, because the length property of arrays throws an error if it's set to greater than 2 32 - 1, the safe integer threshold is usually not reached unless the method is called on a non-array object.

Some array methods set the length property of the array object. They always set the value after normalization, so length always ends as an integer.

Array-like objects

The term array-like object refers to any object that doesn't throw during the length conversion process described above. In practice, such object is expected to actually have a length property and to have indexed elements in the range 0 to length - 1 . (If it doesn't have all indices, it will be functionally equivalent to a sparse array .) Any integer index less than zero or greater than length - 1 is ignored when an array method operates on an array-like object.

Many DOM objects are array-like — for example, NodeList and HTMLCollection . The arguments object is also array-like. You can call array methods on them even if they don't have these methods themselves.

Constructor

Creates a new Array object.

Static properties

Returns the Array constructor.

Static methods

Creates a new Array instance from an iterable or array-like object.

Creates a new Array instance from an async iterable, iterable, or array-like object.

Returns true if the argument is an array, or false otherwise.

Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments.

Instance properties

These properties are defined on Array.prototype and shared by all Array instances.

The constructor function that created the instance object. For Array instances, the initial value is the Array constructor.

Contains property names that were not included in the ECMAScript standard prior to the ES2015 version and that are ignored for with statement-binding purposes.

These properties are own properties of each Array instance.

Reflects the number of elements in an array.

Instance methods

Returns the array item at the given index. Accepts negative integers, which count back from the last item.

Returns a new array that is the calling array joined with other array(s) and/or value(s).

Copies a sequence of array elements within an array.

Returns a new array iterator object that contains the key/value pairs for each index in an array.

Returns true if every element in the calling array satisfies the testing function.

Fills all the elements of an array from a start index to an end index with a static value.

Returns a new array containing all elements of the calling array for which the provided filtering function returns true .

Returns the value of the first element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.

Returns the index of the first element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.

Returns the value of the last element in the array that satisfies the provided testing function, or undefined if no appropriate element is found.

Returns the index of the last element in the array that satisfies the provided testing function, or -1 if no appropriate element was found.

Returns a new array with all sub-array elements concatenated into it recursively up to the specified depth.

Returns a new array formed by applying a given callback function to each element of the calling array, and then flattening the result by one level.

Calls a function for each element in the calling array.

Determines whether the calling array contains a value, returning true or false as appropriate.

Returns the first (least) index at which a given element can be found in the calling array.

Joins all elements of an array into a string.

Returns a new array iterator that contains the keys for each index in the calling array.

Returns the last (greatest) index at which a given element can be found in the calling array, or -1 if none is found.

Returns a new array containing the results of invoking a function on every element in the calling array.

Removes the last element from an array and returns that element.

Adds one or more elements to the end of an array, and returns the new length of the array.

Executes a user-supplied "reducer" callback function on each element of the array (from left to right), to reduce it to a single value.

Executes a user-supplied "reducer" callback function on each element of the array (from right to left), to reduce it to a single value.

Reverses the order of the elements of an array in place . (First becomes the last, last becomes first.)

Removes the first element from an array and returns that element.

Extracts a section of the calling array and returns a new array.

Returns true if at least one element in the calling array satisfies the provided testing function.

Sorts the elements of an array in place and returns the array.

Adds and/or removes elements from an array.

Returns a localized string representing the calling array and its elements. Overrides the Object.prototype.toLocaleString() method.

Returns a new array with the elements in reversed order, without modifying the original array.

Returns a new array with the elements sorted in ascending order, without modifying the original array.

Returns a new array with some elements removed and/or replaced at a given index, without modifying the original array.

Returns a string representing the calling array and its elements. Overrides the Object.prototype.toString() method.

Adds one or more elements to the front of an array, and returns the new length of the array.

Returns a new array iterator object that contains the values for each index in the array.

Returns a new array with the element at the given index replaced with the given value, without modifying the original array.

An alias for the values() method by default.

This section provides some examples of common array operations in JavaScript.

Note: If you're not yet familiar with array basics, consider first reading JavaScript First Steps: Arrays , which explains what arrays are , and includes other examples of common array operations.

Create an array

This example shows three ways to create new array: first using array literal notation , then using the Array() constructor, and finally using String.prototype.split() to build the array from a string.

Create a string from an array

This example uses the join() method to create a string from the fruits array.

Access an array item by its index

This example shows how to access items in the fruits array by specifying the index number of their position in the array.

Find the index of an item in an array

This example uses the indexOf() method to find the position (index) of the string "Banana" in the fruits array.

Check if an array contains a certain item

This example shows two ways to check if the fruits array contains "Banana" and "Cherry" : first with the includes() method, and then with the indexOf() method to test for an index value that's not -1 .

Append an item to an array

This example uses the push() method to append a new string to the fruits array.

Remove the last item from an array

This example uses the pop() method to remove the last item from the fruits array.

Note: pop() can only be used to remove the last item from an array. To remove multiple items from the end of an array, see the next example.

Remove multiple items from the end of an array

This example uses the splice() method to remove the last 3 items from the fruits array.

Truncate an array down to just its first N items

This example uses the splice() method to truncate the fruits array down to just its first 2 items.

Remove the first item from an array

This example uses the shift() method to remove the first item from the fruits array.

Note: shift() can only be used to remove the first item from an array. To remove multiple items from the beginning of an array, see the next example.

Remove multiple items from the beginning of an array

This example uses the splice() method to remove the first 3 items from the fruits array.

Add a new first item to an array

This example uses the unshift() method to add, at index 0 , a new item to the fruits array — making it the new first item in the array.

Remove a single item by index

This example uses the splice() method to remove the string "Banana" from the fruits array — by specifying the index position of "Banana" .

Remove multiple items by index

This example uses the splice() method to remove the strings "Banana" and "Strawberry" from the fruits array — by specifying the index position of "Banana" , along with a count of the number of total items to remove.

Replace multiple items in an array

This example uses the splice() method to replace the last 2 items in the fruits array with new items.

Iterate over an array

This example uses a for...of loop to iterate over the fruits array, logging each item to the console.

But for...of is just one of many ways to iterate over any array; for more ways, see Loops and iteration , and see the documentation for the every() , filter() , flatMap() , map() , reduce() , and reduceRight() methods — and see the next example, which uses the forEach() method.

Call a function on each element in an array

This example uses the forEach() method to call a function on each element in the fruits array; the function causes each item to be logged to the console, along with the item's index number.

Merge multiple arrays together

This example uses the concat() method to merge the fruits array with a moreFruits array, to produce a new combinedFruits array. Notice that fruits and moreFruits remain unchanged.

Copy an array

This example shows three ways to create a new array from the existing fruits array: first by using spread syntax , then by using the from() method, and then by using the slice() method.

All built-in array-copy operations ( spread syntax , Array.from() , Array.prototype.slice() , and Array.prototype.concat() ) create shallow copies . If you instead want a deep copy of an array, you can use JSON.stringify() to convert the array to a JSON string, and then JSON.parse() to convert the string back into a new array that's completely independent from the original array.

You can also create deep copies using the structuredClone() method, which has the advantage of allowing transferable objects in the source to be transferred to the new copy, rather than just cloned.

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, or alias, to the original array; that is, the original array's name and the new variable name are just two names for the exact same object (and so will always evaluate as strictly equivalent ). Therefore, if you make any changes at all either to the value of the original array or to the value of the new variable, the other will change, too:

Creating a two-dimensional array

The following creates a chessboard as a two-dimensional array of strings. The first move is made by copying the 'p' in board[6][4] to board[4][4] . The old position at [6][4] is made blank.

Here is the output:

Using an array to tabulate a set of values

Creating an array using the result of a match.

The result of a match between a RegExp and a string can create a JavaScript array that has properties and elements which provide information about the match. Such an array is returned by RegExp.prototype.exec() and String.prototype.match() .

For example:

For more information about the result of a match, see the RegExp.prototype.exec() and String.prototype.match() pages.

Mutating initial array in iterative methods

Iterative methods do not mutate the array on which it is called, but the function provided as callbackFn can. The key principle to remember is that only indexes between 0 and arrayLength - 1 are visited, where arrayLength is the length of the array at the time the array method was first called, but the element passed to the callback is the value at the time the index is visited. Therefore:

  • callbackFn will not visit any elements added beyond the array's initial length when the call to the iterative method began.
  • Changes to already-visited indexes do not cause callbackFn to be invoked on them again.
  • If an existing, yet-unvisited element of the array is changed by callbackFn , its value passed to the callbackFn will be the value at the time that element gets visited. Removed elements are not visited.

Warning: Concurrent modifications of the kind described above frequently lead to hard-to-understand code and are generally to be avoided (except in special cases).

The following examples use the forEach method as an example, but other methods that visit indexes in ascending order work in the same way. We will first define a helper function:

Modification to indexes not visited yet will be visible once the index is reached:

Modification to already visited indexes does not change iteration behavior, although the array will be different afterwards:

Inserting n elements at unvisited indexes that are less than the initial array length will make them be visited. The last n elements in the original array that now have index greater than the initial array length will not be visited:

Inserting n elements with index greater than the initial array length will not make them be visited:

Inserting n elements at already visited indexes will not make them be visited, but it shifts remaining elements back by n , so the current index and the n - 1 elements before it are visited again:

Deleting n elements at unvisited indexes will make them not be visited anymore. Because the array has shrunk, the last n iterations will visit out-of-bounds indexes. If the method ignores non-existent indexes (see array methods and empty slots ), the last n iterations will be skipped; otherwise, they will receive undefined :

Deleting n elements at already visited indexes does not change the fact that they were visited before they get deleted. Because the array has shrunk, the next n elements after the current index are skipped. If the method ignores non-existent indexes, the last n iterations will be skipped; otherwise, they will receive undefined :

For methods that iterate in descending order of index, insertion causes elements to be skipped, and deletion causes elements to be visited multiple times. Adjust the code above yourself to see the effects.

Specifications

Specification

Browser compatibility

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • Indexed collections guide
  • ArrayBuffer

Python Tutorial

File handling, python modules, python numpy, python pandas, python matplotlib, python scipy, machine learning, python mysql, python mongodb, python reference, module reference, python how to, python examples, python arrays.

Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.

Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library .

Arrays are used to store multiple values in one single variable:

Create an array containing car names:

What is an Array?

An array is a special variable, which can hold more than one value at a time.

If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

The solution is an array!

An array can hold many values under a single name, and you can access the values by referring to an index number.

Access the Elements of an Array

You refer to an array element by referring to the index number .

Get the value of the first array item:

Modify the value of the first array item:

The Length of an Array

Use the len() method to return the length of an array (the number of elements in an array).

Return the number of elements in the cars array:

Note: The length of an array is always one more than the highest array index.

Advertisement

Looping Array Elements

You can use the for in loop to loop through all the elements of an array.

Print each item in the cars array:

Adding Array Elements

You can use the append() method to add an element to an array.

Add one more element to the cars array:

Removing Array Elements

You can use the pop() method to remove an element from the array.

Delete the second element of the cars array:

You can also use the remove() method to remove an element from the array.

Delete the element that has the value "Volvo":

Note: The list's remove() method only removes the first occurrence of the specified value.

Array Methods

Python has a set of built-in methods that you can use on lists/arrays.

Method Description
Adds an element at the end of the list
Removes all the elements from the list
Returns a copy of the list
Returns the number of elements with the specified value
Add the elements of a list (or any iterable), to the end of the current list
Returns the index of the first element with the specified value
Adds an element at the specified position
Removes the element at the specified position
Removes the first item with the specified value
Reverses the order of the list
Sorts the list

Get Certified

COLOR PICKER

colorpicker

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail: [email protected]

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.

  • 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.

Array assignment and reference in Java

I have initialized array a and assigning reference of a to new array b. Now I initialized a new array c and passed its reference to array a. Since array b is reference to array a, b should have new values that are in c but b is having old values of a. What is the reason behind it? Output is given below -

Anuj Gupta's user avatar

  • Thats fine this is how each programming language works. –  bit-shashank Commented Jun 24, 2017 at 4:27

5 Answers 5

Don't be irritated by the name 'list'. The images are taken from a python visualization, but the principle is the same in Java

Array a is assigned with a new array:

Assigning a

Array b is assigned to the instance behind a :

Assigning b

Array c is assigned with a new array:

Assigning c

And finally a is assigned to the instance behind c , b was not re-assigned and still keeps a reference to the old a :

Re-Assigning a

Images taken from a visualization on pythontutor.com

Felix's user avatar

Suppose you think of an object as a house, and a reference as a piece of paper with the address of a house written on it. a , b , and c are all references. So when you say

you're building a house with 1, 2, 3, 4, and 5 in it; and a is a piece of paper with the address of that house.

b is another reference, which means it's another piece of paper. But it has the address of the same house on it.

Now we build a new house and put 6, 7, and 8 into it. c will be a piece of paper with the address of the new house. When we say a = c , then the slip of paper that used to be a is thrown out, and we make a new piece of paper with the address of the new house. That's the new value of a .

But b was a separate piece of paper. It hasn't changed. Nothing we've done has changed it.

References are like that.

ajb's user avatar

When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.

Nipun's user avatar

When you do b=a b references to a. However when you to a=c a is referring to c, but still b refers to the old object (address of this object as value been assigned and it is constant) a that you assigned because that is what it contains when you assigned.

Unless you reassign it, it won't change.

Suresh Atta's user avatar

This is why:

What is Object Reference Variable?

You have 2 objects (the arrays) and 3 references (a, b, c) to the objects. You're just swapping around where things are pointed.

Tim's user avatar

Your Answer

Reminder: Answers generated by artificial intelligence tools are not allowed on Stack Overflow. Learn more

Sign up or log in

Post as a guest.

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy .

Not the answer you're looking for? Browse other questions tagged java arrays reference or ask your own question .

  • The Overflow Blog
  • The world’s largest open-source business has plans for enhancing LLMs
  • Featured on Meta
  • User activation: Learnings and opportunities
  • Site maintenance - Mon, Sept 16 2024, 21:00 UTC to Tue, Sept 17 2024, 2:00...
  • What does a new user need in a homepage experience on Stack Overflow?
  • Announcing the new Staging Ground Reviewer Stats Widget

Hot Network Questions

  • Explode multiple columns with different lengths
  • How would you address the premises of Schellenberg's non-resistant divine hiddenness argument?
  • Is it really a "space walk" (EVA proper) if you don't get your feet wet (in space)?
  • gpg: Can't check signature: No public key | Debian Raspberry Pi Images
  • Could a Gamma Ray Burst knock a Space Mirror out of orbit?
  • Python script to renumber slide ids inside a pptx presentation
  • Arduino Uno Serial.write() how many bits are actually transmitted at once by UART and effect of baudrate on other interrupts
  • If one is arrested, but has a baby/pet in their house, what are they supposed to do?
  • Young adult fantasy book about a girl who accidentally kills her boyfriend and decides to attend an academy for witches or magic
  • Are these colored sets closed under multiplication?
  • XeLaTeX does not show latin extended characters with stix2
  • Little spikes on mains AC
  • Copyright on song first performed in public
  • What does "иного толка" mean? Is it an obsolete meaning?
  • What was the newest chess piece
  • Seeking a Text-Based Version of Paul Dirac's 1926 Paper on Quantum Mechanics
  • How to make a soundless world
  • マリネする vs. マリネにする "to marinate"
  • Fast leap year check
  • Can the concept of a perfectly good God creating beings vulnerable to sin be philosophically justified?
  • Should I be careful about setting levels too high at one point in a track?
  • Why did the Chinese government call its actual languages 'dialects'? Is this to prevent any subnational separatism?
  • My math professor is Chinese. Is it okay for me to speak Chinese to her in office hours?
  • Find conditions for a cubic to have three positive roots without explicitly using the Root objects?

what is assignment array

Learn Java practically and Get Certified .

Popular Tutorials

Popular examples, reference materials, learn java interactively, java introduction.

  • Get Started With Java
  • Your First Java Program
  • Java Comments

Java Fundamentals

  • Java Variables and Literals
  • Java Data Types (Primitive)
  • Java Operators
  • Java Basic Input and Output
  • Java Expressions, Statements and Blocks

Java Flow Control

  • Java if...else Statement
  • Java Ternary Operator
  • Java for Loop

Java for-each Loop

  • Java while and do...while Loop
  • Java break Statement
  • Java continue Statement
  • Java switch Statement

Java Arrays

Java Multidimensional Arrays

Java Copy Arrays

Java OOP(I)

  • Java Class and Objects
  • Java Methods
  • Java Method Overloading
  • Java Constructors
  • Java Static Keyword
  • Java Strings
  • Java Access Modifiers
  • Java this Keyword
  • Java final keyword
  • Java Recursion
  • Java instanceof Operator

Java OOP(II)

  • Java Inheritance
  • Java Method Overriding
  • Java Abstract Class and Abstract Methods
  • Java Interface
  • Java Polymorphism
  • Java Encapsulation

Java OOP(III)

  • Java Nested and Inner Class
  • Java Nested Static Class
  • Java Anonymous Class
  • Java Singleton Class
  • Java enum Constructor
  • Java enum Strings
  • Java Reflection
  • Java Package
  • Java Exception Handling
  • Java Exceptions
  • Java try...catch
  • Java throw and throws
  • Java catch Multiple Exceptions
  • Java try-with-resources
  • Java Annotations
  • Java Annotation Types
  • Java Logging
  • Java Assertions
  • Java Collections Framework
  • Java Collection Interface
  • Java ArrayList
  • Java Vector
  • Java Stack Class
  • Java Queue Interface
  • Java PriorityQueue
  • Java Deque Interface
  • Java LinkedList
  • Java ArrayDeque
  • Java BlockingQueue
  • Java ArrayBlockingQueue
  • Java LinkedBlockingQueue
  • Java Map Interface
  • Java HashMap
  • Java LinkedHashMap
  • Java WeakHashMap
  • Java EnumMap
  • Java SortedMap Interface
  • Java NavigableMap Interface
  • Java TreeMap
  • Java ConcurrentMap Interface
  • Java ConcurrentHashMap
  • Java Set Interface
  • Java HashSet Class
  • Java EnumSet
  • Java LinkedHashSet
  • Java SortedSet Interface
  • Java NavigableSet Interface
  • Java TreeSet
  • Java Algorithms
  • Java Iterator Interface
  • Java ListIterator Interface

Java I/o Streams

  • Java I/O Streams
  • Java InputStream Class
  • Java OutputStream Class
  • Java FileInputStream Class
  • Java FileOutputStream Class
  • Java ByteArrayInputStream Class
  • Java ByteArrayOutputStream Class
  • Java ObjectInputStream Class
  • Java ObjectOutputStream Class
  • Java BufferedInputStream Class
  • Java BufferedOutputStream Class
  • Java PrintStream Class

Java Reader/Writer

  • Java File Class
  • Java Reader Class
  • Java Writer Class
  • Java InputStreamReader Class
  • Java OutputStreamWriter Class
  • Java FileReader Class
  • Java FileWriter Class
  • Java BufferedReader
  • Java BufferedWriter Class
  • Java StringReader Class
  • Java StringWriter Class
  • Java PrintWriter Class

Additional Topics

  • Java Keywords and Identifiers
  • Java Operator Precedence
  • Java Bitwise and Shift Operators
  • Java Scanner Class
  • Java Type Casting
  • Java Wrapper Class
  • Java autoboxing and unboxing
  • Java Lambda Expressions
  • Java Generics
  • Nested Loop in Java
  • Java Command-Line Arguments

Java Tutorials

Java Math max()

  • Java Math min()
  • Java ArrayList trimToSize()

An array is a collection of similar types of data.

For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names.

Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed.

  • How to declare an array in Java?

In Java, here is how we can declare an array.

  • dataType - it can be primitive data types like int , char , double , byte , etc. or Java objects
  • arrayName - it is an identifier

For example,

Here, data is an array that can hold values of type double .

But, how many elements can array this hold?

Good question! To define the number of elements that an array can hold, we have to allocate memory for the array in Java. For example,

Here, the array can store 10 elements. We can also say that the size or length of the array is 10.

In Java, we can declare and allocate the memory of an array in one single statement. For example,

  • How to Initialize Arrays in Java?

In Java, we can initialize arrays during declaration. For example,

Here, we have created an array named age and initialized it with the values inside the curly brackets.

Note that we have not provided the size of the array. In this case, the Java compiler automatically specifies the size by counting the number of elements in the array (i.e. 5).

In the Java array, each memory location is associated with a number. The number is known as an array index. We can also initialize arrays in Java, using the index number. For example,

Elements are stored in the array

  • Array indices always start from 0. That is, the first element of an array is at index 0.
  • If the size of an array is n , then the last element of the array will be at index n-1 .
  • How to Access Elements of an Array in Java?

We can access the element of an array using the index number. Here is the syntax for accessing elements of an array,

Let's see an example of accessing array elements using index numbers.

Example: Access Array Elements

In the above example, notice that we are using the index number to access each element of the array.

We can use loops to access all the elements of the array at once.

  • Looping Through Array Elements

In Java, we can also loop through each element of the array. For example,

Example: Using For Loop

In the above example, we are using the for Loop in Java to iterate through each element of the array. Notice the expression inside the loop,

Here, we are using the length property of the array to get the size of the array.

We can also use the for-each loop to iterate through the elements of an array. For example,

Example: Using the for-each Loop

  • Example: Compute Sum and Average of Array Elements

In the above example, we have created an array of named numbers . We have used the for...each loop to access each element of the array.

Inside the loop, we are calculating the sum of each element. Notice the line,

Here, we are using the length attribute of the array to calculate the size of the array. We then calculate the average using:

As you can see, we are converting the int value into double . This is called type casting in Java. To learn more about typecasting, visit Java Type Casting .

  • Multidimensional Arrays

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare multidimensional arrays in Java.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an array itself. For example,

Here, we have created a multidimensional array named matrix. It is a 2-dimensional array. To learn more, visit the Java multidimensional array .

  • Java Copy Array
  • Java Program to Print an Array
  • Java Program to Concatenate two Arrays
  • Java ArrayList to Array and Array to ArrayList
  • Java Dynamic Array

Table of Contents

  • Introduction

Before we wrap up, let’s put your knowledge of Java Array (With Examples) to the test! Can you solve the following challenge?

Write a function to calculate the average of an array of numbers.

  • Return the average of all numbers in the array arr with the size arrSize .
  • For example, if arr[] = {10, 20, 30, 40} and arrSize = 4 , the expected output is 25 .

Sorry about that.

Our premium learning platform, created with over a decade of experience and thousands of feedbacks .

Learn and improve your coding skills like never before.

  • Interactive Courses
  • Certificates
  • 2000+ Challenges

Related Tutorials

Java Tutorial

Java Library

  • C++ Data Types
  • C++ Input/Output
  • C++ Pointers
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management

In C++, an array is a data structure that is used to store multiple values of similar data types in a contiguous memory location.

For example , if we have to store the marks of 4 or 5 students then we can easily store them by creating 5 different variables but what if we want to store marks of 100 students or say 500 students then it becomes very challenging to create that numbers of variable and manage them. Now, arrays come into the picture that can do it easily by just creating an array of the required size.

Arrays-in-C++

Properties of Arrays in C++

  • An Array is a collection of data of the same data type, stored at a contiguous memory location.
  • Indexing of an array starts from 0. It means the first element is stored at the 0th index, the second at 1st, and so on.
  • Elements of an array can be accessed using their indices.
  • Once an array is declared its size remains constant throughout the program.
  • An array can have multiple dimensions.
  • The size of the array in bytes can be determined by the sizeof operator using which we can also find the number of elements in the array.
  • We can find the size of the type of elements stored in an array by subtracting adjacent addresses.

Array Declaration in C++

In C++, we can declare an array by simply specifying the data type first and then the name of an array with its size.

  • int: It is the type of data to be stored in the array. We can also use other data types such as char, float, and double.
  • arr: It is the name of the array.
  • 5: It is the size of the array which means only 5 elements can be stored in the array.

array declaration in c++

Initialization of Array in C++

In C++, we can initialize an array in many ways but we will discuss some most common ways to initialize an array. We can initialize an array at the time of declaration or after declaration.

1. Initialize Array with Values in C++

We have initialized the array with values. The values enclosed in curly braces ‘{}’ are assigned to the array. Here, 1 is stored in arr[0], 2 in arr[1], and so on. Here the size of the array is 5.

2. Initialize Array with Values and without Size in C++

We have initialized the array with values but we have not declared the length of the array, therefore, the length of an array is equal to the number of elements inside curly braces.

3. Initialize Array after Declaration (Using Loops)

We have initialized the array using a loop after declaring the array. This method is generally used when we want to take input from the user or we cant to assign elements one by one to each index of the array. We can modify the loop conditions or change the initialization values according to requirements.

4. Initialize an array partially in C++

Here, we have declared an array ‘partialArray’ with size ‘5’ and with values ‘1’ and ‘2’ only. So, these values are stored at the first two indices, and at the rest of the indices ‘0’ is stored.

5. Initialize the array with zero in C++

We can initialize the array with all elements as ‘0’ by specifying ‘0’ inside the curly braces. This will happen in case of zero only if we try to initialize the array with a different value say ‘2’ using this method then ‘2’ is stored at the 0th index only.

Accessing an Element of an Array in C++

Elements of an array can be accessed by specifying the name of the array, then the index of the element enclosed in the array subscript operator []. For example, arr[i].

Example 1: The C++ Program to Illustrate How to Access Array Elements

Update array element.

To update an element in an array, we can use the index which we want to update enclosed within the array subscript operator and assign the new value.

Traverse an Array in C++

We can traverse over the array with the help of a loop using indexing in C++. First, we have initialized an array ‘table_of_two’ with a multiple of 2. After that, we run a for loop from 0 to 9 because in an array indexing starts from zero. Therefore, using the indices we print all values stored in an array.

Example 2: The C++ Program to Illustrate How to Traverse an Array

Size of an array in c++.

In C++, we do not have the length function as in Java to find array size but we can calculate the size of an array using sizeof() operator trick. First, we find the size occupied by the whole array in the memory and then divide it by the size of the type of element stored in the array. This will give us the number of elements stored in the array.

Example 3: The C++ Program to Illustrate How to Find the Size of an Array

Relation between arrays and pointers in c++.

In C++, arrays and pointers are closely related to each other. The array name is treated as a pointer that stored the memory address of the first element of the array. As we have discussed earlier, In array elements are stored at contiguous memory locations that’s why we can access all the elements of an array using the array name.

Example 4: Illustrating the Relationship between Array and Pointers

Explanation:

In the above code, we first define an array “ arr ” and then declare a pointer “ ptr ” and assign the array “arr” to it. We are able to assign arr to ptr because arr is also a pointer. After that, we print the memory address of arr using reference operator ( & ) and also print the address stored in pointer ptr and we can see arr and ptr, both stores the same memory address.

Example 5: Printing Array Elements without Indexing in C++

We generally access and print the array elements using indexing. For example to access the first element we use array_name[0]. We have discussed above that the array name is a pointer that stored the address of the first element and array elements are stored at contiguous locations. Now, we are going to access the elements of an array using the array name only.

Explanation

In the above code, we first declared an array “ arr ” with four elements. After that, we are printing the array elements. Let’s discuss how we do it. We discussed that the array name is a pointer that stores the address of the first element of an array so, to print the first element we have dereferenced that pointer (*arr) using dereferencing operator (*) which prints the data stored at that address.

To print the second element of an array we first add 1 to arr which is equivalent to (address of arr + size_of_one_element *1) that takes the pointer to the address just after the first one and after that, we dereference that pointer to print the second element. Similarly, we print rest of the elements of an array without using indexing.

Passing Array to Function in C++

To use arrays efficiently we should know how to pass arrays to function. We can pass arrays to functions as an argument same as we pass variables to functions but we know that the array name is treated as a pointer using this concept we can pass the array to functions as an argument and then access all elements of that array using pointer.

So ultimately, arrays are always passed as pointers to the function. Let’s see 3 ways to pass an array to a function that are majorly used.

1. Passing Array as a Pointer

In this method, we simply pass the array name in function call which means we pass the address to the first element of the array. In this method, we can modify the array elements within the function.

2. Passing Array as an Unsized Array

In this method, the function accepts the array using a simple array declaration with no size as an argument.

3. Passing Array as a Sized Array

In this method, the function accepts the array using a simple array declaration with size as an argument. We use this method by sizing an array just to indicate the size of an array.

Note: Array will be treated as a pointer in the passed function no matter what method we use. As the array are passed as pointers, they will loose the information about its size leading to a phenomenon named as Array Decay.

Example: Illustrating Different Ways to Pass Arrays to a Function

  • Multidimensional Arrays in C++

Arrays declared with more than one dimension are called multidimensional arrays. The most widely used multidimensional arrays are 2D arrays and 3D arrays. These arrays are generally represented in the form of rows and columns.

Multidimensional Array Declaration

  • Data_Type:  Type of data to be stored in the array.
  • Array_Name:  Name of the array.
  • Size1, Size2,…, SizeN:  Size of each dimension.

Two Dimensional Array in C++

In C++, a two-dimensional array is a grouping of elements arranged in rows and columns. Each element is accessed using two indices: one for the row and one for the column, which makes it easy to visualize as a table or grid.

Syntax of 2D array

  • n: Number of rows.

two dimensional array in c++

Example: The C++ Program to Illustrate the Two-Dimensional Array

In the above code we have declared a 2D array with 4 rows and 4 columns after that we initialized the array with the value of (i+j) in every iteration of the loop. Then we are printing the 2D array using a nested loop and we can see in the below output that there are 4 rows and 4 columns.

Three-Dimensional Array in C++

The 3D array uses three dimensions. A collection of various two-dimensional arrays piled on top of one another can be used to represent it. Three indices—the row index, column index, and depth index are used to uniquely identify each element in a 3D array.

Declaration of Three-Dimensional Array in C++

To declare a 3D array in C++, we need to specify its third dimension along with 2D dimensions.

  • Data_Type:  Type of data to be stored in each element.
  • Array_Name:  Name of the array
  • D:  Number of 2D arrays or Depth of array.
  • R:  Number of rows in each 2D array.
  • C:  Number of columns in each 2D array.

three dimensional array in  c++

Example: The C++ Program to Illustrate the 3d Array

In the above code, we have declared a 3D array and then initialized it using three nested for loops. After that, we printed all layers of the 3D array again using three nested for loops as seen in the output.

Related Articles

  • Properties of Array
  • Array Decay

author

Please Login to comment...

Similar reads.

  • OpenAI o1 AI Model Launched: Explore o1-Preview, o1-Mini, Pricing & Comparison
  • How to Merge Cells in Google Sheets: Step by Step Guide
  • How to Lock Cells in Google Sheets : Step by Step Guide
  • PS5 Pro Launched: Controller, Price, Specs & Features, How to Pre-Order, and More
  • #geekstreak2024 – 21 Days POTD Challenge Powered By Deutsche Bank

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

COMMENTS

  1. C array declaration and assignment?

    Why does C++ support memberwise assignment of arrays within structs, but not generally? Arrays are not pointers. x here does refer to an array, though in many circumstances this "decays" (is implicitly converted) to a pointer to its first element. Likewise, y too is the name of an array, not a pointer. You can do array assignment within structs:

  2. What is Array?

    Array is a linear data structure where all elements are arranged sequentially. It is a collection of elements of same data type stored at contiguous memory locations. For simplicity, we can think of an array as a flight of stairs where on each step is placed a value (let's say one of your friends). Here, you can identify the location of any ...

  3. C Arrays

    Array in C is one of the most used data structures in C programming. It is a simple and fast way of storing multiple values under a single name. In this article, we will study the different aspects of array in C language such as array declaration, definition, initialization, types of arrays, array syntax, advantages and disadvantages, and many more.

  4. C Arrays (With Examples)

    Access Array Elements. You can access elements of an array by indices. Suppose you declared an array mark as above. The first element is mark[0], the second element is mark[1] and so on. Declare an Array Few keynotes: Arrays have 0 as the first index, not 1. In this example, mark[0] is the first element.

  5. c++

    Is it because, array decays to a pointer when passed to a function foo(..), assignment operation is possible. And in main, is it because they are of type int[] which invalidates the assignment operation. Doesn't a,b in both the cases mean the same ? Thanks. Edit 1: When I do it in a function foo, it's assigning the b's starting element location ...

  6. Array Data Structure Guide

    An array is a collection of items of the same variable type that are stored at contiguous memory locations. It's one of the most popular and simple data structures and is often used to implement other data structures. Each item in an array is indexed starting with 0 . Each element in an array is accessed through its index.

  7. Destructuring assignment

    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 ...

  8. Array vs Object Destructuring in JavaScript

    Array destructuring is a unique technique that allows you to neatly extract an array's value into new variables. For instance, without using the array destructuring assignment technique, you would copy an array's value into a new variable like so:

  9. How to Use Array and Object Destructuring in JavaScript

    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 is this necessary?

  10. Arrays (The Java™ Tutorials > Learning the Java Language

    Arrays. An array is a container object that holds a fixed number of values of a single type. The length of an array is established when the array is created. After creation, its length is fixed. You have seen an example of arrays already, in the main method of the "Hello World!" application.

  11. Java Arrays

    Java Arrays. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value. To declare an array, define the variable type with square brackets: We have now declared a variable that holds an array of strings. To insert values to it, you can place the values in a comma-separated list, inside ...

  12. Destructuring assignment

    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.

  13. Array Variable Assignment in Java

    Array Variable Assignment in Java. An array is a collection of similar types of data in a contiguous location in memory. After Declaring an array we create and assign it a value or variable. During the assignment variable of the array things, we have to remember and have to check the below condition. 1.

  14. Array

    The Array object, as with arrays in other programming languages, enables storing a collection of multiple items under a single variable name, and has members for performing common array operations. ... 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 ...

  15. C++ Arrays (With Examples)

    C++ Arrays. In C++, an array is a variable that can store multiple values of the same type. For example, Suppose a class has 27 students, and we need to store all their grades. Instead of creating 27 separate variables, we can simply create an array: double grade[27]; Here, grade is an array that can hold a maximum of 27 elements of double type.

  16. JavaScript Arrays

    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.

  17. Arrays in Java

    Do refer to default array values in Java. Obtaining an array is a two-step process. First, you must declare a variable of the desired array type. Second, you must allocate the memory to hold the array, using new, and assign it to the array variable. Thus, in Java, all arrays are dynamically allocated.

  18. Python Arrays

    Python Variables Variable Names Assign Multiple Values Output Variables Global Variables Variable Exercises. ... An array is a special variable, which can hold more than one value at a time. If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this: ...

  19. Array assignment and reference in Java

    1. When you assigned value of a to b, it means b is referring to same space allocated to array a. This means b will pick up any changes made to the array a, but if any changes made to the variable a. If a is made to refer to new array, b will still refer the old a reference.

  20. Java Array (With Examples)

    An array is a collection of similar types of data. For example, if we want to store the names of 100 people then we can create an array of the string type that can store 100 names. String[] array = new String[100]; Here, the above array cannot store more than 100 names. The number of values in a Java array is always fixed.

  21. C++ Arrays

    Properties of Arrays in C++. An Array is a collection of data of the same data type, stored at a contiguous memory location. Indexing of an array starts from 0. It means the first element is stored at the 0th index, the second at 1st, and so on. Elements of an array can be accessed using their indices.