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

An array is a special variable, which can hold more than one value:

Why Use Arrays?

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.

Creating an Array

Using an array literal is the easiest way to create a JavaScript Array.

It is a common practice to declare arrays with the const keyword.

Learn more about const with arrays in the chapter: JS Array Const .

Spaces and line breaks are not important. A declaration can span multiple lines:

You can also create an array, and then provide the elements:

Using the JavaScript Keyword new

The following example also creates an Array, and assigns values to it:

The two examples above do exactly the same.

There is no need to use new Array() .

For simplicity, readability and execution speed, use the array literal method.

Advertisement

Accessing Array Elements

You access an array element by referring to the index number :

Note: Array indexes start with 0.

[0] is the first element. [1] is the second element.

Changing an Array Element

This statement changes the value of the first element in cars :

Converting an Array to a String

The JavaScript method toString() converts an array to a string of (comma separated) array values.

Access the Full Array

With JavaScript, the full array can be accessed by referring to the array name:

Arrays are Objects

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

But, JavaScript arrays are best described as arrays.

Arrays use numbers to access its "elements". In this example, person[0] returns John:

Objects use names to access its "members". In this example, person.firstName returns John:

Array Elements Can Be Objects

JavaScript variables can be objects. Arrays are special kinds of objects.

Because of this, you can have variables of different types in the same Array.

You can have objects in an Array. You can have functions in an Array. You can have arrays in an Array:

Array Properties and Methods

The real strength of JavaScript arrays are the built-in array properties and methods:

Array methods are covered in the next chapters.

The length Property

The length property of an array returns the length of an array (the number of array elements).

The length property is always one more than the highest array index.

Accessing the First Array Element

Accessing the last array element, looping array elements.

One way to loop through an array, is using a for loop:

You can also use the Array.forEach() function:

Adding Array Elements

The easiest way to add a new element to an array is using the push() method:

New element can also be added to an array using the length property:

Adding elements with high indexes can create undefined "holes" in an array:

Associative Arrays

Many programming languages support arrays with named indexes.

Arrays with named indexes are called associative arrays (or hashes).

JavaScript does not support arrays with named indexes.

In JavaScript, arrays always use numbered indexes .  

WARNING !! If you use named indexes, JavaScript will redefine the array to an object.

After that, some array methods and properties will produce incorrect results .

 Example:

The difference between arrays and objects.

In JavaScript, arrays use numbered indexes .  

In JavaScript, objects use named indexes .

Arrays are a special kind of objects, with numbered indexes.

When to Use Arrays. When to use Objects.

  • JavaScript does not support associative arrays.
  • You should use objects when you want the element names to be strings (text) .
  • You should use arrays when you want the element names to be numbers .

JavaScript new Array()

JavaScript has a built-in array constructor new Array() .

But you can safely use [] instead.

These two different statements both create a new empty array named points:

These two different statements both create a new array containing 6 numbers:

The new keyword can produce some unexpected results:

A Common Error

is not the same as:

How to Recognize an Array

A common question is: How do I know if a variable is an array?

The problem is that the JavaScript operator typeof returns " object ":

The typeof operator returns object because a JavaScript array is an object.

Solution 1:

To solve this problem ECMAScript 5 (JavaScript 2009) defined a new method Array.isArray() :

Solution 2:

The instanceof operator returns true if an object is created by a given constructor:

Nested Arrays and Objects

Values in objects can be arrays, and values in arrays can be objects:

To access arrays inside arrays, use a for-in loop for each array:

Complete Array Reference

For a complete Array reference, go to our:

Complete JavaScript Array Reference .

The reference contains descriptions and examples of all Array properties and methods.

Test Yourself With Exercises

Get the value " Volvo " from the cars array.

Start the Exercise

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.

Home » JavaScript Tutorial » JavaScript Arrays

JavaScript Arrays

Summary : in this tutorial, you’ll learn about JavaScript arrays and their basic operations.

Introduction to JavaScript arrays

In JavaScript, an array is an ordered list of values. Each value is called an element specified by an index :

A JavaScript array has the following characteristics:

  • First, an array can hold values of mixed types. For example, you can have an array that stores elements with the types number, string, boolean, and null.
  • Second, the size of an array is dynamic and auto-growing. In other words, you don’t need to specify the array size up front.

Creating JavaScript arrays

JavaScript provides you with two ways to create an array.  The first one is to use the Array constructor as follows:

The scores  array is empty, which does hold any elements.

If you know the number of elements that the array will hold, you can create an array with an initial size as shown in the following example:

To create an array and initialize it with some elements, you pass the elements as a comma-separated list into the Array() constructor.

For example, the following creates the scores array that has five elements (or numbers):

Note that if you use the Array() constructor to create an array and pass a number into it, you are creating an array with an initial size.

However, when you pass a value of another type like string into the Array() constructor, you create an array with an element of that value. For example:

JavaScript allows you to omit the new operator when you use the Array() constructor. For example, the following statement creates the  artists array.

In practice, you’ll rarely use the Array() constructor to create an array.

The more preferred way to create an array is to use the array literal notation:

The array literal form uses the square brackets [] to wrap a comma-separated list of elements.

The following example creates the colors array that holds string elements:

To create an empty array, you use square brackets without specifying any element like this:

Accessing JavaScript array elements

JavaScript arrays are zero-based indexed. In other words, the first element of an array starts at index 0, the second element starts at index 1, and so on.

To access an element in an array, you specify an index in the square brackets [] :

The following shows how to access the elements of the mountains array:

To change the value of an element, you assign that value to the element like this:

Getting the array size

Typically, the length property of an array returns the number of elements. The following example shows how to use the length property:

Basic operations on arrays

The following explains some basic operations on arrays. You’ll learn advanced operations such as map() , filter() , and reduce() in the next tutorials.

1) Adding an element to the end of an array

To add an element to the end of an array, you use the push() method:

2) Adding an element to the beginning of an array

To add an element to the beginning of an array, you use the unshift() method:

3) Removing an element from the end of an array

To remove an element from the end of an array, you use the pop() method:

4) Removing an element from the beginning of an array

To remove an element from the beginning of an array, you use the shift() method:

5) Finding an index of an element in the array

To find the index of an element, you use the indexOf() method:

Declaration

There are two syntaxes for creating an empty array:

Almost all the time, the second syntax is used. We can supply initial elements in the brackets:

Array elements are numbered, starting with zero.

We can get an element by its number in square brackets:

We can replace an element:

…Or add a new one to the array:

The total count of the elements in the array is its length :

We can also use alert to show the whole array.

An array can store elements of any type.

For instance:

An array, just like an object, may end with a comma:

The “trailing comma” style makes it easier to insert/remove items, because all lines become alike.

Get last elements with “at”

Let’s say we want the last element of the array.

Some programming languages allow the use of negative indexes for the same purpose, like fruits[-1] .

Although, in JavaScript it won’t work. The result will be undefined , because the index in square brackets is treated literally.

We can explicitly calculate the last element index and then access it: fruits[fruits.length - 1] .

A bit cumbersome, isn’t it? We need to write the variable name twice.

Luckily, there’s a shorter syntax: fruits.at(-1) :

In other words, arr.at(i) :

  • is exactly the same as arr[i] , if i >= 0 .
  • for negative values of i , it steps back from the end of the array.

Methods pop/push, shift/unshift

A queue is one of the most common uses of an array. In computer science, this means an ordered collection of elements which supports two operations:

  • push appends an element to the end.
  • shift get an element from the beginning, advancing the queue, so that the 2nd element becomes the 1st.

Arrays support both operations.

In practice we need it very often. For example, a queue of messages that need to be shown on-screen.

There’s another use case for arrays – the data structure named stack .

It supports two operations:

  • push adds an element to the end.
  • pop takes an element from the end.

So new elements are added or taken always from the “end”.

A stack is usually illustrated as a pack of cards: new cards are added to the top or taken from the top:

For stacks, the latest pushed item is received first, that’s also called LIFO (Last-In-First-Out) principle. For queues, we have FIFO (First-In-First-Out).

Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements, both to/from the beginning or the end.

In computer science, the data structure that allows this, is called deque .

Methods that work with the end of the array:

Extracts the last element of the array and returns it:

Both fruits.pop() and fruits.at(-1) return the last element of the array, but fruits.pop() also modifies the array by removing it.

Append the element to the end of the array:

The call fruits.push(...) is equal to fruits[fruits.length] = ... .

Methods that work with the beginning of the array:

Extracts the first element of the array and returns it:

Add the element to the beginning of the array:

Methods push and unshift can add multiple elements at once:

An array is a special kind of object. The square brackets used to access a property arr[0] actually come from the object syntax. That’s essentially the same as obj[key] , where arr is the object, while numbers are used as keys.

They extend objects providing special methods to work with ordered collections of data and also the length property. But at the core it’s still an object.

Remember, there are only eight basic data types in JavaScript (see the Data types chapter for more info). Array is an object and thus behaves like an object.

For instance, it is copied by reference:

…But what makes arrays really special is their internal representation. The engine tries to store its elements in the contiguous memory area, one after another, just as depicted on the illustrations in this chapter, and there are other optimizations as well, to make arrays work really fast.

But they all break if we quit working with an array as with an “ordered collection” and start working with it as if it were a regular object.

For instance, technically we can do this:

That’s possible, because arrays are objects at their base. We can add any properties to them.

But the engine will see that we’re working with the array as with a regular object. Array-specific optimizations are not suited for such cases and will be turned off, their benefits disappear.

The ways to misuse an array:

  • Add a non-numeric property like arr.test = 5 .
  • Make holes, like: add arr[0] and then arr[1000] (and nothing between them).
  • Fill the array in the reverse order, like arr[1000] , arr[999] and so on.

Please think of arrays as special structures to work with the ordered data . They provide special methods for that. Arrays are carefully tuned inside JavaScript engines to work with contiguous ordered data, please use them this way. And if you need arbitrary keys, chances are high that you actually require a regular object {} .

Performance

Methods push/pop run fast, while shift/unshift are slow.

Why is it faster to work with the end of an array than with its beginning? Let’s see what happens during the execution:

It’s not enough to take and remove the element with the index 0 . Other elements need to be renumbered as well.

The shift operation must do 3 things:

  • Remove the element with the index 0 .
  • Move all elements to the left, renumber them from the index 1 to 0 , from 2 to 1 and so on.
  • Update the length property.

The more elements in the array, the more time to move them, more in-memory operations.

The similar thing happens with unshift : to add an element to the beginning of the array, we need first to move existing elements to the right, increasing their indexes.

And what’s with push/pop ? They do not need to move anything. To extract an element from the end, the pop method cleans the index and shortens length .

The actions for the pop operation:

The pop method does not need to move anything, because other elements keep their indexes. That’s why it’s blazingly fast.

The similar thing with the push method.

One of the oldest ways to cycle array items is the for loop over indexes:

But for arrays there is another form of loop, for..of :

The for..of doesn’t give access to the number of the current element, just its value, but in most cases that’s enough. And it’s shorter.

Technically, because arrays are objects, it is also possible to use for..in :

But that’s actually a bad idea. There are potential problems with it:

The loop for..in iterates over all properties , not only the numeric ones.

There are so-called “array-like” objects in the browser and in other environments, that look like arrays . That is, they have length and indexes properties, but they may also have other non-numeric properties and methods, which we usually don’t need. The for..in loop will list them though. So if we need to work with array-like objects, then these “extra” properties can become a problem.

The for..in loop is optimized for generic objects, not arrays, and thus is 10-100 times slower. Of course, it’s still very fast. The speedup may only matter in bottlenecks. But still we should be aware of the difference.

Generally, we shouldn’t use for..in for arrays.

A word about “length”

The length property automatically updates when we modify the array. To be precise, it is actually not the count of values in the array, but the greatest numeric index plus one.

For instance, a single element with a large index gives a big length:

Note that we usually don’t use arrays like that.

Another interesting thing about the length property is that it’s writable.

If we increase it manually, nothing interesting happens. But if we decrease it, the array is truncated. The process is irreversible, here’s the example:

So, the simplest way to clear the array is: arr.length = 0; .

new Array()

There is one more syntax to create an array:

It’s rarely used, because square brackets [] are shorter. Also, there’s a tricky feature with it.

If new Array is called with a single argument which is a number, then it creates an array without items, but with the given length .

Let’s see how one can shoot themselves in the foot:

To avoid such surprises, we usually use square brackets, unless we really know what we’re doing.

Multidimensional arrays

Arrays can have items that are also arrays. We can use it for multidimensional arrays, for example to store matrices:

Arrays have their own implementation of toString method that returns a comma-separated list of elements.

Also, let’s try this:

Arrays do not have Symbol.toPrimitive , neither a viable valueOf , they implement only toString conversion, so here [] becomes an empty string, [1] becomes "1" and [1,2] becomes "1,2" .

When the binary plus "+" operator adds something to a string, it converts it to a string as well, so the next step looks like this:

Don’t compare arrays with ==

Arrays in JavaScript, unlike some other programming languages, shouldn’t be compared with operator == .

This operator has no special treatment for arrays, it works with them as with any objects.

Let’s recall the rules:

  • Two objects are equal == only if they’re references to the same object.
  • If one of the arguments of == is an object, and the other one is a primitive, then the object gets converted to primitive, as explained in the chapter Object to primitive conversion .
  • …With an exception of null and undefined that equal == each other and nothing else.

The strict comparison === is even simpler, as it doesn’t convert types.

So, if we compare arrays with == , they are never the same, unless we compare two variables that reference exactly the same array.

For example:

These arrays are technically different objects. So they aren’t equal. The == operator doesn’t do item-by-item comparison.

Comparison with primitives may give seemingly strange results as well:

Here, in both cases, we compare a primitive with an array object. So the array [] gets converted to primitive for the purpose of comparison and becomes an empty string '' .

Then the comparison process goes on with the primitives, as described in the chapter Type Conversions :

So, how to compare arrays?

That’s simple: don’t use the == operator. Instead, compare them item-by-item in a loop or using iteration methods explained in the next chapter.

Array is a special kind of object, suited to storing and managing ordered data items.

The declaration:

The call to new Array(number) creates an array with the given length, but without elements.

  • The length property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods.
  • If we shorten length manually, the array is truncated.

Getting the elements:

  • we can get element by its index, like arr[0]
  • also we can use at(i) method that allows negative indexes. For negative values of i , it steps back from the end of the array. If i >= 0 , it works same as arr[i] .

We can use an array as a deque with the following operations:

  • push(...items) adds items to the end.
  • pop() removes the element from the end and returns it.
  • shift() removes the element from the beginning and returns it.
  • unshift(...items) adds items to the beginning.

To loop over the elements of the array:

  • for (let i=0; i<arr.length; i++) – works fastest, old-browser-compatible.
  • for (let item of arr) – the modern syntax for items only,
  • for (let i in arr) – never use.

To compare arrays, don’t use the == operator (as well as > , < and others), as they have no special treatment for arrays. They handle them as any objects, and it’s not what we usually want.

Instead you can use for..of loop to compare arrays item-by-item.

We will continue with arrays and study more methods to add, remove, extract elements and sort arrays in the next chapter Array methods .

Is array copied?

What is this code going to show?

The result is 4 :

That’s because arrays are objects. So both shoppingCart and fruits are the references to the same array.

Array operations.

Let’s try 5 array operations.

  • Create an array styles with items “Jazz” and “Blues”.
  • Append “Rock-n-Roll” to the end.
  • Replace the value in the middle with “Classics”. Your code for finding the middle value should work for any arrays with odd length.
  • Strip off the first value of the array and show it.
  • Prepend Rap and Reggae to the array.

The array in the process:

Calling in an array context

What is the result? Why?

The call arr[2]() is syntactically the good old obj[method]() , in the role of obj we have arr , and in the role of method we have 2 .

So we have a call of the function arr[2] as an object method. Naturally, it receives this referencing the object arr and outputs the array:

The array has 3 values: initially it had two, plus the function.

Sum input numbers

Write the function sumInput() that:

  • Asks the user for values using prompt and stores the values in the array.
  • Finishes asking when the user enters a non-numeric value, an empty string, or presses “Cancel”.
  • Calculates and returns the sum of array items.

P.S. A zero 0 is a valid number, please don’t stop the input on zero.

Run the demo

Please note the subtle, but important detail of the solution. We don’t convert value to number instantly after prompt , because after value = +value we would not be able to tell an empty string (stop sign) from the zero (valid number). We do it later instead.

A maximal subarray

The input is an array of numbers, e.g. arr = [1, -2, 3, 4, -9, 6] .

The task is: find the contiguous subarray of arr with the maximal sum of items.

Write the function getMaxSubSum(arr) that will return that sum.

If all items are negative, it means that we take none (the subarray is empty), so the sum is zero:

Please try to think of a fast solution: O(n 2 ) or even O(n) if you can.

Open a sandbox with tests.

Slow solution

We can calculate all possible subsums.

The simplest way is to take every element and calculate sums of all subarrays starting from it.

For instance, for [-1, 2, 3, -9, 11] :

The code is actually a nested loop: the external loop over array elements, and the internal counts subsums starting with the current element.

The solution has a time complexity of O(n 2 ) . In other words, if we increase the array size 2 times, the algorithm will work 4 times longer.

For big arrays (1000, 10000 or more items) such algorithms can lead to serious sluggishness.

Fast solution

Let’s walk the array and keep the current partial sum of elements in the variable s . If s becomes negative at some point, then assign s=0 . The maximum of all such s will be the answer.

If the description is too vague, please see the code, it’s short enough:

The algorithm requires exactly 1 array pass, so the time complexity is O(n).

You can find more detailed information about the algorithm here: Maximum subarray problem . If it’s still not obvious why that works, then please trace the algorithm on the examples above, see how it works, that’s better than any words.

Open the solution with tests in a sandbox.

  • If you have suggestions what to improve - please submit a GitHub issue or a pull request instead of commenting.
  • If you can't understand something in the article – please elaborate.
  • To insert few words of code, use the <code> tag, for several lines – wrap them in <pre> tag, for more than 10 lines – use a sandbox ( plnkr , jsbin , codepen …)

Lesson navigation

  • © 2007—2024  Ilya Kantor
  • about the project
  • terms of usage
  • privacy policy

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 Constructor Function

  • JavaScript console.log()

JavaScript Destructuring Assignment

  • JavaScript Destructuring

The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variables . For example, Before ES6:

Note : The order of the name does not matter in object destructuring.

For example, you could write the above program as:

Note : When destructuring objects, you should use the same name for the variable as the corresponding object key.

For example,

If you want to assign different variable names for the object key, you can use:

  • Array Destructuring

You can also perform array destructuring in a similar way. For example,

  • Assign Default Values

You can assign the default values for variables while using destructuring. For example,

In the above program, arrValue has only one element. Hence,

  • the x variable will be 10
  • the y variable takes the default value 7

In object destructuring, you can pass default values in a similar way. For example,

  • Swapping Variables

In this example, two variables are swapped using the destructuring assignment syntax.

You can skip unwanted items in an array without assigning them to local variables. For example,

In the above program, the second element is omitted by using the comma separator , .

Assign Remaining Elements to a Single Variable

You can assign the remaining elements of an array to a variable using the spread syntax ... . For example,

Here, one is assigned to the x variable. And the rest of the array elements are assigned to y variable.

You can also assign the rest of the object properties to a single variable. For example,

Note : The variable with the spread syntax cannot have a trailing comma , . You should use this rest element (variable with spread syntax) as the last variable.

  • Nested Destructuring Assignment

You can perform nested destructuring for array elements. For example,

Here, the variable y and z are assigned nested elements two and three .

In order to execute the nested destructuring assignment, you have to enclose the variables in an array structure (by enclosing inside [] ).

You can also perform nested destructuring for object properties. For example,

In order to execute the nested destructuring assignment for objects, you have to enclose the variables in an object structure (by enclosing inside {} ).

Note : Destructuring assignment feature was introduced in ES6 . Some browsers may not support the use of the destructuring assignment. Visit Javascript Destructuring support to learn more.

Table of Contents

  • Skipping Items
  • Arbitrary Number of Elements

Sorry about that.

Related Tutorials

JavaScript Tutorial

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.

array assignment javascript

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.

array assignment javascript

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

How Destructuring Works in JavaScript – Explained with Code Examples

Sahil Mahapatra

Destructuring is a powerful JavaScript feature introduced in ES6 (ECMAScript 2015). It makes it easier to extract values from arrays or properties from objects and assign them to variables in a readable way.

Let's delve into how destructuring works and explore various use cases with examples.

You can get the source code from here .

Table of Contents

  • What is Destructuring ?

Array Destructuring

Object destructuring, what is destructuring.

Destructuring is a technique that allows you to unpack values from arrays or objects into separate variables.

This process involves breaking down complex data structures into simpler parts, making it easier to work with them.

Let's start with array destructuring. We'll use the following example.

Without destructuring, extracting values from an array can be verbose:

Here, you're accessing each element of the hobbies array using index notation and assigning them to individual variables.

Destructuring simplifies this process into a single line of code, like this:

In this example, you're extracting the values from the hobbies array and assigning them to variables firstHobby , secondHobby , and thirdHobby , respectively.

Skipping Elements from the Array

You can choose to ignore certain elements by omitting them from the destructuring pattern:

In this example, you're destructuring the hobbies array but only assigning values to the firstHobby and thirdHobby variables. You're skipping the second element in the array by placing a comma without a variable name between firstHobby and thirdHobby . This allows you to extract specific elements from the array while ignoring others, providing more flexibility and control in your destructuring patterns.

Nested Array Destructuring

Array destructuring can also be nested. Here's an example:

In this code, we have a nested array nestedArray . Using nested array destructuring, you're extracting values from both the outer and inner arrays and assigning them to variables firstValue , secondValue , thirdValue , and fourthValue .

Moving on to object destructuring, consider the following object:

Regular Destructuring

Object destructuring allows you to extract properties from objects:

In this example, { name, age, city } is the destructuring syntax. It means you're extracting the name , age , and city properties from the person object and assigning them to variables of the same name. So name will have the value "John Doe" , age will have 30 , and city will have "New York" .

Destructuring with Different Names

You can assign extracted properties to variables with different names:

In this example, you're using a syntax like { name: personName, age: personAge, city: personCity } which allows you to assign extracted properties to variables with different names. Here, name from the person object is assigned to personName , age is assigned to personAge , and city is assigned to personCity .

Having Default Values while Destructuring

You can also provide default values for object properties:

Here, you're providing a default value "Unknown" for the gender property in case it's not present in the person object. If gender is not defined in person , the variable gender will default to "Unknown" .

Nested Objects

Object destructuring supports nested objects:

In this example, { name, address: { city, country } } is the destructuring syntax. You're extracting the name property directly from the person object. Then within the address object, you're extracting the city and country properties. So city will have the value "New York" , and country will default to undefined assuming address does not have a country property.

That's it! You should now have a good understanding of how JavaScript destructuring works for arrays and objects.

Feel free to experiment with the code examples to further solidify your understanding. If you have any feedback or questions, please contact me on Twitter or Linkedin . Happy learning!

Read more posts .

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

Navigation Menu

Search code, repositories, users, issues, pull requests..., provide feedback.

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly.

To see all available qualifiers, see our documentation .

  • Notifications

SabaZain/Arrays-Assignment-1-to-12

Folders and files.

  • JavaScript 50.3%
  • TypeScript 49.7%
  • 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
  • Sum and Product of Array elements using JavaScript
  • JavaScript Program to Find Sum of elements in a Matrix
  • JavaScript Program to Find Sum of Odd Numbers in an Array
  • JavaScript Program to Find Largest Element in an Array
  • JavaScript Program to Determine the Length of an Array
  • Add Elements to a JavaScript Array
  • Find the OR and AND of Array elements using JavaScript
  • JavaScript Program for Sum of Digits of a Number
  • Javascript Program for Maximum equilibrium sum in an array
  • Javascript Program for Equilibrium index of an array
  • How to find the sum of all elements of a given array in JavaScript ?
  • Javascript Program for Mean of range in array
  • How to Add Elements to the End of an Array in JavaScript ?
  • Find the min/max element of an Array using JavaScript
  • JavaScript program to print even numbers in an array
  • RMS Value Of Array in JavaScript
  • Java Program to Find Sum of Array Elements
  • Program to find sum of elements in a given array
  • Sum of absolute differences of all pairs in a given array

JavaScript Program of Absolute Sum of Array Elements

Using JavaScript , one can find the absolute sum of all elements present in an array. Below is an example to understand the problem clearly.

There are several approaches for finding the absolute sum of array elements using JavaScript which are as follows:

Table of Content

Brute Force Approach

Using array.reduce() method.

Declare a function which takes an array as its parameter and initialize a variable sum to store the sum of absolute values of array elements. Use a for loop to iterate through each element of the array. Inside the loop, use the Math.abs() function to get the absolute value of each element and add it to the sum variable. Return the final sum.

Example: To demonstration finding absolute sum of array elements using brute force approach.

Time complexity: O(n)

Space complexity: O(1)

Declare a function which takes an array as its parameter. Use the reduce() method on the input array arr. Inside the reduce() method, accumulate the sum by adding the absolute value of each element (Math.abs(num)) to the accumulator (sum). Start with an initial value of 0 for the accumulator. Return the final accumulated sum.

Example: Demonstration of finding Absolute sum of array elements using Array.reduce().

Please Login to comment...

Similar reads.

  • JavaScript-Program
  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

  • skip navigation All Products Product Bundles DevCraft All Telerik .NET tools and Kendo UI JavaScript components in one package. Now enhanced with: NEW : Design Kits for Figma

How to Implement Function Overloading in TypeScript

' title=

Function overloading is a TypeScript feature that lets us define a function that accepts different kinds of arguments.

TypeScript mainly adds data type-checking capabilities that are missing in JavaScript. This makes programming easier since we don’t have to check the data type of variables and other values ourselves.

We can write our JavaScript programs in TypeScript. Then we can compile the TypeScript code into JavaScript so it can be run by JavaScript runtimes like the browser and Node.js.

One useful feature that is available in TypeScript is function overloading. Function overloading is a feature that lets us define a function that accepts different kinds of arguments.

In this article, we will look at how to implement function overloading in our TypeScript code.

Function Overloading in TypeScript

With TypeScript, we can define a function that accepts different kinds of arguments with function overloading.

To use this, we just have to add all the possible signatures for a function for the combinations of arguments we want the function to accept.

For example, to implement function overloading in TypeScript, we can write something like the following:

We have two different signatures for the add function and they both have a return type set to number .

The first signature expects that both parameters a and b are numbers. And the second signature expects that both parameters a and b are strings.

To implement the function, we make a and b accept the unknown type, which lets us pass in anything for a and b .

In the function body, we check the data types of a and b with the typeof operator. If a and b are both strings, we convert a and b to numbers with the Number function and then get the sum of the numbers. If they’re both numbers, then we just return the sum of them. Otherwise, we return 0.

The unknown type is a type-safe counterpart of any . We can’t assign values with unknown type to any variable. But we can convert unknown type values to something else that matches the type of the variable.

With the typeof checks, we narrowed the types of a and b to one data type so TypeScript can infer the type and do the operations for the variables with the inferred type.

Then we can call add by writing:

We call add with the values that are expected by at least one of the signatures, so it passes the type checks done by the TypeScript compiler.

If we call add with values that aren’t expected by any of the signatures like:

Then the TypeScript compiler will raise a type-check error.

The function implementation’s signature must be more general than the overload signatures. This way, the function with overloads can accept different kinds of values expected by at least one of the signatures.

Method Overloading

We can also overload constructor or class methods.

For instance, we can write something like:

We define the Greeter class with the greet method in it. The greet method is overloaded with two different signatures. The first takes a string and returns a string . The second takes a string array and also returns a string .

In the implementation, we make the person function have an unknown type. We can add a return type or omit it since the TypeScript compiler can infer the return type from the implementation. We can check the value of person in the implementation with our own type checks.

First we check if person is a string with typeof person === "string" . Then we check if person is an array with Array.isArray .

Next, we can create a Greeter instance and call the greet method by writing:

We create a Greeter instance with new . And then we call greet on the instance either with a string or an array of strings we specified with the signatures.

When to Use Function Overloading?

Ideally, we use function overloading only when we expect required arguments that have different types.

The examples above all have required parameters only but they’re allowed to have different types. If we expect some arguments that are optional, then we can use the optional parameter syntax instead.

For instance, instead of writing something like:

We can replace the overloads with optional parameters by writing something like:

Since we accept param1 and param2 as optional parameters, we can use ? to denote them as such.

Function overloading is a feature in TypeScript that lets us define a function that accepts different kinds of arguments.

We can use function overloading for specifying any kinds of function parameters. But ideally, we use them only for required parameters since TypeScript already has a simple optional function parameters syntax.

We can have function overloads for regular functions and class methods.

' title=

John Au-Yeung

John Au-Yeung is a frontend developer with 6+ years of experience. He is an avid blogger (visit his site at https://thewebdev.info/ ) and the author of Vue.js 3 By Example .

Related Posts

How my team accidentally moved to typescript and loved it, fully typed with trpc, pattern matching with typescript, all articles.

  • ASP.NET Core
  • ASP.NET MVC
  • ASP.NET AJAX
  • Blazor Desktop/.NET MAUI
  • Design Systems
  • Document Processing
  • Accessibility

array assignment javascript

Latest Stories in Your Inbox

Subscribe to be the first to get our expert-written articles and tutorials for developers!

All fields are required

Loading animation

Progress collects the Personal Information set out in our Privacy Policy and the Supplemental Privacy notice for residents of California and other US States and uses it for the purposes stated in that policy.

You can also ask us not to share your Personal Information to third parties here: Do Not Sell or Share My Info

By submitting this form, I understand and acknowledge my data will be processed in accordance with Progress' Privacy Policy .

I agree to receive email communications from Progress Software or its Partners , containing information about Progress Software’s products. I understand I may opt out from marketing communication at any time here or through the opt out option placed in the e-mail communication received.

By submitting this form, you understand and agree that your personal data will be processed by Progress Software or its Partners as described in our Privacy Policy . You may opt out from marketing communication at any time here or through the opt out option placed in the e-mail communication sent by us or our Partners.

We see that you have already chosen to receive marketing materials from us. If you wish to change this at any time you may do so by clicking here .

Thank you for your continued interest in Progress. Based on either your previous activity on our websites or our ongoing relationship, we will keep you updated on our products, solutions, services, company news and events. If you decide that you want to be removed from our mailing lists at any time, you can change your contact preferences by clicking here .

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • Português (do Brasil)

JavaScript ( JS ) is a lightweight interpreted (or just-in-time compiled) programming language with first-class functions . While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js , Apache CouchDB and Adobe Acrobat . JavaScript is a prototype-based , multi-paradigm, single-threaded , dynamic language, supporting object-oriented, imperative, and declarative (e.g. functional programming) styles.

JavaScript's dynamic capabilities include runtime object construction, variable parameter lists, function variables, dynamic script creation (via eval ), object introspection (via for...in and Object utilities ), and source-code recovery (JavaScript functions store their source text and can be retrieved through toString() ).

This section is dedicated to the JavaScript language itself, and not the parts that are specific to Web pages or other host environments. For information about APIs that are specific to Web pages, please see Web APIs and DOM .

The standards for JavaScript are the ECMAScript Language Specification (ECMA-262) and the ECMAScript Internationalization API specification (ECMA-402). As soon as one browser implements a feature, we try to document it. This means that cases where some proposals for new ECMAScript features have already been implemented in browsers, documentation and examples in MDN articles may use some of those new features. Most of the time, this happens between the stages 3 and 4, and is usually before the spec is officially published.

Do not confuse JavaScript with the Java programming language — JavaScript is not "Interpreted Java" . Both "Java" and "JavaScript" are trademarks or registered trademarks of Oracle in the U.S. and other countries. However, the two programming languages have very different syntax, semantics, and use.

JavaScript documentation of core language features (pure ECMAScript , for the most part) includes the following:

  • The JavaScript guide
  • The JavaScript reference

For more information about JavaScript specifications and related technologies, see JavaScript technologies overview .

Learn how to program in JavaScript with guides and tutorials.

For complete beginners

Head over to our Learning Area JavaScript topic if you want to learn JavaScript but have no previous experience with JavaScript or programming. The complete modules available there are as follows:

Answers some fundamental questions such as "what is JavaScript?", "what does it look like?", and "what can it do?", along with discussing key JavaScript features such as variables, strings, numbers, and arrays.

Continues our coverage of JavaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events.

The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you.

Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server.

Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work.

JavaScript guide

A much more detailed guide to the JavaScript language, aimed at those with previous programming experience either in JavaScript or another language.

Intermediate

JavaScript frameworks are an essential part of modern front-end web development, providing developers with proven tools for building scalable, interactive web applications. This module gives you some fundamental background knowledge about how client-side frameworks work and how they fit into your toolset, before moving on to a series of tutorials covering some of today's most popular ones.

An overview of the basic syntax and semantics of JavaScript for those coming from other programming languages to get up to speed.

Overview of available data structures in JavaScript.

JavaScript provides three different value comparison operations: strict equality using === , loose equality using == , and the Object.is() method.

How different methods that visit a group of object properties one-by-one handle the enumerability and ownership of properties.

A closure is the combination of a function and the lexical environment within which that function was declared.

Explanation of the widely misunderstood and underestimated prototype-based inheritance.

Memory life cycle and garbage collection in JavaScript.

JavaScript has a runtime model based on an "event loop".

Browse the complete JavaScript reference documentation.

Get to know standard built-in objects Array , Boolean , Date , Error , Function , JSON , Math , Number , Object , RegExp , String , Map , Set , WeakMap , WeakSet , and others.

Learn more about the behavior of JavaScript's operators instanceof , typeof , new , this , the operator precedence , and more.

Learn how do-while , for-in , for-of , try-catch , let , var , const , if-else , switch , and more JavaScript statements and keywords work.

Learn how to work with JavaScript's functions to develop your applications.

JavaScript classes are the most appropriate way to do object-oriented programming.

IMAGES

  1. JavaScript ES6:Destructuring for Beginners

    array assignment javascript

  2. Working with Javascript Array includes() method with examples for Beginners

    array assignment javascript

  3. How to create an arrays in JavaScript?

    array assignment javascript

  4. JavaScript Array from()

    array assignment javascript

  5. Array methods in Javascript aka Javascript Array Methods Cookbook

    array assignment javascript

  6. Array assignment and reference in Java

    array assignment javascript

VIDEO

  1. 1st Assignment JavaScript/ Type script in a governor house onsite class

  2. Array in Real Life

  3. JavaScript Array Destructuring Part 2 [شرح جافا سكريبت]

  4. Day 5: JavaScript Array and JSON

  5. React JS

  6. ✅ JavaScript Object

COMMENTS

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

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

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

  4. JavaScript Arrays

    Another way to create an array is to use the new keyword with the Array constructor. Here is the basic syntax: new Array(); If a number parameter is passed into the parenthesis, that will set the length for the new array. In this example, we are creating an array with a length of 3 empty slots. new Array(3)

  5. Destructuring in JavaScript

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

  6. The JavaScript Array Handbook

    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.

  7. ES6 Destructuring Assignment Explained By Examples

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

  8. The Beginner's Guide to JavaScript Array with Examples

    JavaScript provides you with two ways to create an array. The first one is to use the Array constructor as follows: let scores = new Array (); Code language: JavaScript (javascript) The scores array is empty, which does hold any elements. If you know the number of elements that the array will hold, you can create an array with an initial size ...

  9. Arrays

    The call to new Array(number) creates an array with the given length, but without elements. The length property is the array length or, to be precise, its last numeric index plus one. It is auto-adjusted by array methods. If we shorten length manually, the array is truncated. Getting the elements: we can get element by its index, like arr[0]

  10. JavaScript Destructuring Assignment

    JavaScript Destructuring. The destructuring assignment introduced in ES6 makes it easy to assign array values and object properties to distinct variables. For example, Before ES6: // assigning object attributes to variables const person = {. name: 'Sara', age: 25, gender: 'female'. }

  11. JavaScript Arrays: Create, Access, Add & Remove Elements

    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.

  12. javascript

    32. There are a couple of ways to append an array in JavaScript: 1) The push() method adds one or more elements to the end of an array and returns the new length of the array. Output: 2) The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array: Output:

  13. JavaScript Array Tutorial

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

  14. Destructuring Assignment in JavaScript

    Destructuring Assignment is a JavaScript expression that allows to unpack values from arrays, or properties from objects, into distinct variables data can be extracted from arrays, objects, nested objects and assigning to variables. In Destructuring Assignment on the left-hand side defined that which value should be unpacked from the sourced ...

  15. How Destructuring Works in JavaScript

    Destructuring is a powerful JavaScript feature introduced in ES6 (ECMAScript 2015). It makes it easier to extract values from arrays or properties from objects and assign them to variables in a readable way. Let's delve into how destructuring works and explore various use cases with examples. You can get

  16. javascript assignment operator array

    When your "test" function returns, you're correct that "names" is "gone". However, its value is not, because it's been assigned to a global variable. The value of the "names" local variable was a reference to an array object. That reference was copied into the global variable, so now that global variable also contains a reference to the array object.

  17. GitHub

    JavaScript50.3%. TypeScript49.7%. Contribute to SabaZain/Arrays-Assignment-1-to-12 development by creating an account on GitHub.

  18. JavaScript Program of Absolute Sum of Array Elements

    Using JavaScript, one can find the absolute sum of all elements present in an array. Below is an example to understand the problem clearly. Example: Input: [ -4, -7, 3, 10, 12] Output: 36. Explanation: Absolute values: 4 + 7 + 3 + 10 + 12 = 36. There are several approaches for finding the absolute sum of array elements using JavaScript which ...

  19. How to Implement Function Overloading in TypeScript

    We can't assign values with unknown type to any variable. But we can convert unknown type values to something else that matches the type of the variable. With the typeof checks, we narrowed the types of a and b to one data type so TypeScript can infer the type and do the operations for the variables with the inferred type.

  20. JavaScript

    JavaScript (JS) is a lightweight interpreted (or just-in-time compiled) programming language with first-class functions. While it is most well-known as the scripting language for Web pages, many non-browser environments also use it, such as Node.js, Apache CouchDB and Adobe Acrobat. JavaScript is a prototype-based, multi-paradigm, single-threaded, dynamic language, supporting object-oriented ...