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:

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

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

[email protected]

Top Tutorials

Top references, top examples, get certified.

How to Convert a String to an Array in JavaScript

javascript create array of strings

  • Introduction

Textual data is typically stored through sequences of characters - strings. These sequences, are ultimately, arrays, and converting between the two structures typically is both simple and intuitive. Whether you're breaking a word down into its characters, or a sentence into words - splitting a string into an array isn't an uncommon operation, and most languages have built-in methods for this task.

In this guide, learn how to convert a String to an Array in JavaScript, with the split() , Object.assign() , Array.from() methods and spread[...] operator, as well as when to use which.
  • Split String into Array with split()

The split() method is used to divide a string into an ordered list of two or more substrings, depending on the pattern/divider/delimiter provided, and returns it. The pattern/divider/delimiter is the first parameter in the method's call and can be a regular expression , a single character , or another string .

If you'd like to learn more about Regular Expressions - read our Guide to Regular Expressions and Matching Strings in JavaScript !

For example, suppose we have a string:

We could split it on each whitespace (breaking it down into words), or on every character, or any other arbitrary delimiter, such as 'p' :

One of the major downsides of using single characters or even entire strings is that the approach is fairly rigid. You can't match by multiple delimiters, unless you use a Regular Expression. For instance, say you'd like to break a string into sentences . A sentence can end with a period ( . ), exclamation mark ( ! ), a question mark ( ? ) or three dots ( ... ). Each of these are valid sentences, but we'd have to perform multiple splits to match all of them, if we were to use single characters or strings.

Pattern matching is where Regular Expressions excel! Let's split a string on each sentence, with any of these ending delimiters:

However, the delimiters are lost! We split on them and in the process, remove them from the output. Additionally, we have multiple whitespaces in the beginnings of the sentences, and there's an empty string in the end! This isn't to say that split() doesn't work well with Regular Expressions - but it is to say that splitting sentences out of text isn't solved well by split() . This is where we can use the match() method instead - which returns the matching patterns and their delimiters:

Again, if you're interested in learning more about Regular Expressions - read our Guide to Regular Expressions and Matching Strings in JavaScript !

Note: The split() method takes in a second parameter, which specifies the limit of splitting that can occur. It doesn't alter the number of splits and elements to fit the passed argument, but rather, performs the split n times, from the start, and stops splitting after that.

To limit the number of splits we perform, we can easily supply the second argument of the split() method:

A common use case for the split() method is when someone supplies their full name as a single string:

Here, we can split the name and save it as different fields of an object to the database, for instance:

Instead of having to call get both elements using an array index, we can use array destructuring to make the assignment cleaner:

Note: The split() method doesn't support certain UTF-8 characters, such as emojis (i.e. 😄, 😍, ⁣💗), and will replace them with a pair of �� .

  • Split String into Array with Array.from()

The from() method from the Array class is the leading contender to the split() method. It's used to create an array, given a source of data - and naturally, it can be used to create an array from an iterable string :

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

The major benefit of using Array.from() instead of split() is that you don't have to bother with setting a delimiter - the constituent elements are just re-exposed and added to an array, rather than being converted explicitly. Additionally, the Array.from() method supports emoji characters:

  • Split String into Array with the Spread Operator

The Spread Operator has several uses and is a widely-applicable operator in JavaScript. In our context - we'd be most interested in expanding arrays (strings are arrays of characters).

If you'd like to learn more about the Spread Operator - read our Spread Operator in JavaScript !

The operator's syntax is simple and clean - and we can spread out the string into an array :

The operator also works with UTF-8 emojis:

  • Split String with Object.assign()

The Object.assign() method copies all values and properties of one object - and maps them to the properties of another. In a sense - it's used for cloning objects and merging those with the same properties:

In our case - we'd be copying and mapping the values within a string onto an array:

This approach is a bit more verbose, and less aesthetically pleasing than the previous two:

It's worth noting that Object.assign() doesn't support special UTF-8 characters such as emojis:

In this short guide, we've taken a look at how to convert a string into an array in JavaScript. We've explored the split() method, which has the highest level of customizability - including splitting on Regular Expressions! Then, we've explored the creation of arrays from() sources such as strings. The Spread Operator works very well in expanding strings back to arrays, and we've finally covered the Object.assign() method to assign the values of a string to an array.

You might also like...

  • JavaScript: Check if First Letter of a String is Upper Case
  • Using Mocks for Testing in JavaScript with Sinon.js
  • For-each Over an Array in JavaScript
  • Commenting Code in JavaScript - Types and Best Practices

Improve your dev skills!

Get tutorials, guides, and dev jobs in your inbox.

No spam ever. Unsubscribe at any time. Read our Privacy Policy.

Frontend Developer & Technical Writer

In this article

javascript create array of strings

React State Management with Redux and Redux-Toolkit

Coordinating state and keeping components in sync can be tricky. If components rely on the same data but do not communicate with each other when...

David Landup

Getting Started with AWS in Node.js

Build the foundation you'll need to provision, deploy, and run Node.js applications in the AWS cloud. Learn Lambda, EC2, S3, SQS, and more!

© 2013- 2024 Stack Abuse. All rights reserved.

  • Trending Categories

Data Structure

  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary

How to create an array of strings in JavaScript?

To create an array of strings in JavaScript, simply assign values −

You can also use the new keyword to create an array of strings in JavaScript −

The Array parameter is a list of strings or integers. When you specify a single numeric parameter with the Array constructor, you specify the initial length of the array. The maximum length allowed for an array is 4,294,967,295.

Let’s see an example to create arrays in JavaScript −

V Jyothi

Related Articles

  • How to create array of strings in Java?
  • How to create an array of integers in JavaScript?
  • How to convert array of decimal strings to array of integer strings without decimal in JavaScript
  • How to convert array of strings to array of numbers in JavaScript?
  • How to create an array of partial objects from another array in JavaScript?
  • How to create multi-line strings in JavaScript?
  • How to Create an Array using Intersection of two Arrays in JavaScript?
  • How can I convert an array to an object by splitting strings? JavaScript
  • How to dynamically create radio buttons using an array in JavaScript?
  • JavaScript filter an array of strings, matching case insensitive substring?
  • How to create a string by joining the elements of an array in JavaScript?
  • Finding all the Longest Strings from an Array in JavaScript
  • Removing consecutive duplicates from strings in an array using JavaScript
  • How to create an array with random values with the help of JavaScript?
  • How to trim all strings in an array in PHP ?

Kickstart Your Career

Get certified by completing the course

  • Read Tutorial
  • Watch Guide Video
  • Complete the Exercise

In this guide, we're going to start working through what arrays are in JavaScript and how we can work with them.

There are two main ways that you can create an array and we're going to use the first syntax which is essentially a generated syntax where we create a new array object. And so I'm going to store it in a variable called generatedArray and the syntax for this is new which is a special keyword and then array. Now there are a couple of ways to do this. Say that you want an array with three elements inside of it, we can pass it in just like this.

And this will create the array for us.

If I say generatedArray now you can see that we have 3 items. They're all undefined. But we do have a collection. We could even call generatedArray length and you can see that we have three items in this array. Now having 3 undefine items may not seem very helpful. So let's go and let's create a new array with some names so I can create some baseball player names here.

And now if I run

this generatedArray you can see that we have a collection of three individuals and three strings. So that is one way that you can generate an array. I don't use that way too often and the only time I'll usually use it is when I want to create an array and I don't know what the values are going to be, but I happen to know how many elements are going to be inside and then I use exactly what I did up here.

The more common way that I create an array is by creating what is called the array literal syntax . And so here is a VAR literal array. Obviously you could call it anything you want and here it is simply going to be using the brackets. And so I can put inside of these three items and run it. And now I have a literal array just like that.

Now I could obviously mix these. So those are using integers but if I wanted to I could put strings inside of it. So if I go literal array again I can reassign it to these values. And now if I call literal array it has Altuve, Correa, and Spring which is supposed to be Springer the baseball player.

I can also do just like before, I can call link that has that attribute associated with it so that those are the two most common ways.

Now I've shown you how you can have integers and I've shown you how you can have strings. But JavaScript is incredibly flexible and you can mix and match the elements in the data types inside of your arrays. So let's create a new one called mixed array. And with this mixed array you'll see we can combine anything that we want. For the most part. So I can say hi and put a integer. I can't even put another array. So I could but the ABC's is right here and this is going to be a nested array inside of it.

Make sure you separate each one with the comma and then from there I can even put in objects. Here I can put an object with a name, close the object out and the last one we're going to do may seem a little bit tricky but I can actually put a function in here as well. I could say function greeting and then inside of it console log 'hey there' and then also close it off obviously.

And we have our mixedArray, so that should show you could put literally anything you want. It's a collection of data but JavaScript is a much more flexible with what you can put inside of your arrays than many other languages. Many languages like C or Java in those ones you have to declare the type of elements that are going to be inside of an array and that's because they have very strict compiler requirements. whereas, the JavaScript engine is much more flexible and what it allows. So that's how you can create arrays.

Now let's talk about how we can actually get things out of the arrays. So let's start with our most basic one. If we go back to literal array here the syntax for getting items out is what's called the bracket syntax so you put two brackets right here. And then inside of it you call the index of the item that you want to pull out. Early on in this course I talked about indexes in computer science starting with 0 instead of 1. We discussed that when we're talking about how we could count the characters and grab characters from a string.

We can follow the same pattern when working with arrays so right here if we want Altuve, we can pass in zero and remember it's because arrays and indexes in general start with zero.

If I hit return, that pulls out Altuve and now I can use it however I want. So a very common pattern you'll see is to do something like this. I can say player name and then call the literalArray and this time let's go with the next item which is going to be 1. So I store it and now if I call player name you can see it's stored with Correa and that is very common kind of pattern that you will see in development.

Now that is helpful but you may still kind of be wondering when in the world am I going to use this? That's a very common question to ask especially if you are new to development. Arrays are incredibly handy for a number of scenarios. One of the most common that I use them for is with database queries. Usually when you're building an application and you make a query to a database or to an API when you receive that data back there has to be a standard representation for how that data is sent back to you. One of the most common is to have data sent as an array and you can then loop over that data show it on the screen. And so that's one of the reasons why it's so important to understand the way that arrays and collections work.

Now let's move down the list a little bit. So we talked about how we can grab a single element. Let's also talk about how we can work with some of those more complex ones.

Remember we have our mixedArray and if I open this up you can see all of the different things that we have inside it. In the zero index, we have "Hi" in the first index, we have the integer 1 then we have an array that has an array inside of it. Then we have a object with a key value pair of name and then Kristine and then we have a function called greeting.

So how exactly can we call some of these other items. Well we already talked about how we could call the first two. Those are pretty basic where we in a call just mixed array and do something like that with the bracket syntax with the next one it may seem like this would be more tricky when you have a nested array. So what we're going to do is pass in the index 2 and whenever you want to reference that that's one thing I love about the javascript console is it gives you a really nice reference point for your indexes and different things like that.

So here I want the array but let's say that I want the "C" in the array and I know it's at the second index, I can pass in a second set of brackets so whenever you have something nested like this then you can do your very first call your very first query and then use the bracket syntax again and chain these together. Now run this and it returns "C" and you could store that in a variable or whatever you want to do with it. When you're working with nested arrays.

Now let's talk about our object. We know it's in the index of 3, and because of that we're going to receive just a plain object back. So if I just say 3, this gives us an object back so don't let the end of the bracket syntax intimidate you because all you need to do is treat it like we've been treating objects this entire course. You can use the dot syntax and chain it together. Now you can have access to that name.

Now let's talk about the last one because this one I've seen trip people up a little bit. So we have our greeting and if you just call 4 that is only going to return the function greeting. But what if we actually want to call the function which is a more standard thing. Well it's going to be the exact same way that we had call a regular function. We've queried it and now we just put our nice parends at the end and it prints out 'hey there' and the function is executed.

Now go a little bit further if you want to do things like be able to have methods inside of objects that is a very common thing to do and you can have those include it and arrays. So one of the easiest ways of understanding the way arrays work in JavaScript is just think of them as a collection of all the regular items that you've been using this entire course. So there's nothing more special about them than that. They collect everything you can put things inside of it.

It's just a way of storing it, when you want to store multiple things inside of the same variable you can. But beyond that you can treat them exactly the same way as when they were just kind of one off items stored inside of variables. So the main thing to understand is how you can properly query each one of those items just like we walk through right here.

  • Source code

devCamp does not support ancient browsers. Install a modern version for best experience.

The JavaScript Array Handbook – JS Array Methods Explained with Examples

In programming, an array is a collection of elements or items. Arrays store data as elements and retrieve them back when you need them.

The array data structure is widely used in all programming languages that support it.

In this handbook, I'll teach you all about arrays in JavaScript. You'll learn about complex data handling, destructuring, the most commonly used array methods, and more.

Why Did I Write this Article?

There are many great articles on JavaScript arrays already available around the internet. So why did I write yet another article on the same subject? What's the motivation?

Well, over the years of interacting with my mentees, I realized that most beginners need a tutorial that covers arrays thoroughly from beginning to end with examples.

So I decided to create such an article chock full of meaningful examples. If you are a beginner at JavaScript, I hope you'll find it very helpful.

But even as an experienced developer, this handbook may come in handy to help you brush up on things as you need. I'm also learning the whole thing again while writing about it. So let's dive in.

What is an Array in JavaScript?

A pair of square brackets [] represents an array in JavaScript. All the elements in the array are comma(,) separated.

In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays.

Here is an example of an array with four elements: type Number, Boolean, String, and Object.

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.

So, for example, in the above array, the element 100 is at index 0 , true is at index 1 , 'freeCodeCamp' is at index 2 , and so on.

The number of elements in the array determines its length. For example, the length of the above array is four.

Interestingly, JavaScript arrays are not of fixed length. You can change the length anytime by assigning a positive numeric value. We will learn more about that in a while.

How to Create an Array in JavaScript

You can create an array in multiple ways in JavaScript. The most straightforward way is by assigning an array value to a variable.

You can also use the Array constructor to create an array.

Please Note: new Array(2) will create an array of length two and none of the elements are defined in it. However, new Array(1,2) will create an array of length two with the elements 1 and 2 in it.

There are other methods like Array.of() and Array.from() , and the spread operator( ... ) helps you create arrays, too. We will learn about them later in this article.

How to Get Elements from an Array in JS

You can access and retrieve elements from an array using its index. You need to use the square bracket syntax to access array elements.

Based on your use-cases, you may choose to access array elements one by one or in a loop.

When you're accessing elements using index like this:

You can use the length of an array to traverse backward and access elements.

You can also loop through the array using a regular for or forEach loop, or any other loop.

And here's the output:

image-30

How to Add Elements to an Array in JS

Use the push() method to insert an element into an array. The push() method adds an element at the end of the array. How about we add some peanuts to the salad, like this:

Now the salad array is:

["🍅", "🍄", "🥦", "🥒", "🌽", "🥕", "🥑", "🥜"]

Note that the push() method adds an element to the end of the array. If you want to add an element to the beginning of the array, you'll need to use the unshift() method.

["🥜", "🍅", "🍄", "🥦", "🥒", "🌽", "🥕", "🥑"]

How to Remove Elements from an Array in JS

The easiest way to remove a single element from an array is using the pop() method. Every time you call the pop() method, it removes an element from the end of the array. Then it returns the removed element and changes the original array.

Use the shift() method to remove an element from the beginning of an array. Like the pop() method, shift() returns the removed element and changes the original array.

How to Copy and Clone an Array in JS

You can copy and clone an array to a new array using the slice() method. Note that the slice() method doesn't change the original array. Instead, it creates a new shallow copy of the original array.

Alternatively, you can use the spread operator to create a copy of the array. We will learn about that soon.

How to Determine if a Value is an Array in JS

You can determine if a value is an array using the Array.isArray(value) method. The method returns true if the passed value is an array.

Array Destructuring in JavaScript

With ECMAScript 6 (ES6), we have some new syntax to extract multiple properties from an array and assign them to variables in one go. It is handy to help you keep your code clean and concise. This new syntax is called destructuring syntax.

Here is an example of extracting the values from an array using the destructuring syntax:

Now you can use the variables in your code:

To do the same thing without the destructuring, it would look like this:

So, the destructuring syntax saves you from writing lots of code. This gives you a massive boost in productivity.

How to Assign a Default Value to a Variable

You can assign a default value using destructuring when there is no value or undefined for the array element.

In the example below, we assign a default value for the mushroom variable.

How to Skip a Value in an Array

With destructuring, you can skip an array element to map to a variable. For example, you may not be interested in all the elements in an array. In that case, skipping a value comes in handy.

In the example below, we skip the mushroom element. Notice the space in the variable declaration at the left side of the expression.

Nested Array Destructuring in JS

In JavaScript, arrays can be nested. This means that an array can have another array as an element. Array nesting can go to any depth.

For example, let's create a nested array for fruits. It has a few fruits and an array of vegetables in it.

How would you access the '🥕' from the above array? Again, you could do this without destructuring, like this:

Alternatively, you could use this short-hand syntax:

You can also access it using the destructuring syntax, like this:

How to Use the Spread Syntax and Rest Parameter in JavaScript

Since ES6, we can use the ... (yes, three consecutive dots) as spread syntax and the rest parameter in array destructuring.

  • For the rest parameter, the ... appears on the left side of the destructuring syntax.
  • For the spread syntax, the ... appears on the right side of the destructuring syntax.

How to Use the Rest Parameter in JS

With Rest Parameter , we can map out the left elements of an array in a new array. The rest parameter must be the last variable in the destructuring syntax.

In the example below, we have mapped the first two of the array elements to the tomato and mushroom variables. The remaining elements are mapped to the rest variable using the ... . The rest variable is a new array containing the leftover elements.

How to Use the Spread Operator in JS

With the spread operator, we can create a clone/copy of an existing array like this:

Destructuring Use Cases in JavaScript

Let's look at a few exciting use-cases of array destructuring, the spread operator, and the rest parameter.

How to Swap Values with Destructuring

We can swap the value of two variables easily using the array destructuring syntax.

How to Merge Arrays

We can merge two arrays and create a new array with all the elements from both arrays. Let's take two arrays — one with a couple of smiley faces and another with a few veggies.

Now, we will merge them to create a new array.

JavaScript Array Methods

So far, we have seen a few array properties and methods. Let's do a quick recap of the ones we've looked at:

  • push() – Insert an element at the end of the array.
  • unshift() – Insert an element at the beginning of the array.
  • pop() – Remove an element from the end of the array.
  • shift() – Remove an element from the beginning of the array.
  • slice() – Create a shallow copy of an array.
  • Array.isArray() – Determine if a value is an array.
  • length – Determine the size of an array.

Now we'll learn about other important JS array methods with examples.

How to Create, Remove, Update, and Access Arrays in JavaScript

In this section, we will learn about methods you can use to create a new array, remove elements to make the array empty, access elements, and many more.

The concat() array method

The concat() method merges one or more arrays and returns a merged array. It is an immutable method. This means it doesn't change (mutate) existing arrays.

Let's concat two arrays.

Using the concat() method we can merge more than two arrays. We can merge any number of arrays with this syntax:

Here is an example:

The join() array method

The join() method joins all the elements of the array using a separator and returns a string. The default separator used for joining is comma(,) .

You can pass a separator of your choice to join the elements. Here is an example of joining the elements with a custom separator:

Invoking the join() method on an empty array returns an empty string:

The fill() array method

The fill() method fills an array with a static value. You can change all the elements to a static value or change a few selected items. Note that the fill() method changes the original array.

Here is an example where we are changing only the last two elements of the array using the fill() method:

In this case, the first argument of the fill() method is the value we change with. The second argument is the start index to change. It starts with 0 . The last argument is to determine where to stop filling. The max value of it could be colors.length .

Please check out this Twitter thread for a practical use of the fill() method.

Have you used the #JavaScript array fill() method in practice yet? It fills all the array elements with a static value. 🧵 👇 #DEVCommunity #100DaysOfCode pic.twitter.com/ahfsJBOacT — Tapas Adhikary (@tapasadhikary) February 12, 2021

Also, you may find this demo project helpful: https://github.com/atapas/array-fill-color-cards .

The includes() array method

You can determine the presence on an element in an array using the includes() method. If the element is found, the method returns true , and false otherwise.

The indexOf() array method

You may want to know the index position of an element in array. You can use the indexOf() method to get that. It returns the index of the first occurrence of an element in the array. If an element is not found, the indexOf() method returns -1 .

There is another method lastIndexOf() that helps you find the index of the last occurrence of an element in the array. Like indexOf() , lastIndexOf() also returns -1 if the element is not found.

The reverse() array method

As the name suggests, the reverse() method reverses the elements' positions in the array so that the last element goes into the first position and the first one to the last.

The reverse() method modifies the original array.

The sort() array method

The sort() method is probably one of the most often used array methods. The default sort() method converts the element types into strings and then sorts them. The default sorting order is ascending. The sort() method changes the original array.

The sort() method accepts an optional comparator function as an argument. You can write a comparator function and pass to the sort() method to override the default sorting behavior.

Let's now take an array of numbers and sort them in ascending and descending order using a comparator function:

First, we'll invoke the default sort() method and see the output:

Now the sorted array is, [1, 10, 100, 13, 23, 37, 5, 56, 9]. Well, that's not the output we expect. But it happens because the default sort() method converts the elements to a string and then compares them based on the UTF-16 code unit values.

To solve this, let's write a comparator function. Here is one for the ascending order:

Now pass this to the sort() method:

For descending order, do this:

Check out this GitHub repository for more sorting examples and tips: https://github.com/atapas/js-array-sorting

The splice() array method

The splice() method helps you add, update, and remove elements in an array. This method may be a bit confusing at the beginning, but once you know how to use it properly, you will get it right.

The main purpose of the splice() method is to delete elements from array. It returns an array of the elements deleted and modifies the original array. But you can add and replace elements using it as well.

To add an element using the splice() method, we need to pass the position where we want to add, how many elements to delete starting with the position, and the element to add.

In the example below, we are adding an element zack at the index 1 without deleting any elements.

Have a look at the following example. Here we are removing one element from the index 2 (the 3rd element) and adding a new element, zack . The splice() method returns an array with the deleted element, bob .

Check out this Twitter thread to learn how the splice() method helps you make an array empty.

How do you prefer to remove one, many, or all the elements from a #javascript array in a native way? - 🗑️arr.length = 0 - 🗑️arr = [] - 🗑️arr.shift() - 🗑️arr.pop() - 🗑️arr.splice() This is a thread to talk about it. 🧵 #CodeNewbie #100DaysOfCode #DevCommunityIN #DEVCommunity — Tapas Adhikary (@tapasadhikary) October 5, 2020

Static Array Methods in JavaScript

In JavaScript, arrays have three static methods. We have discussed Array.isArray() already. Let's discuss the other two now.

The Array.from() array method

Let's take a simple HTML code snippet that contains a div and a few list elements:

Now we'll query the DOM using the getElementsByTagName() method.

It returns a HTMLCollection that looks like this:

htmlCollec

So it is like an array. Now let's try iterating over it using forEach :

Guess what the output is? It's an error like this:

htmlcolc_error

But why? Because the HTMLCollection is not an array. It is an Array-Like object. So you can not iterate over it using forEach .

htmlCollec_object

This is where you should use the Array.from() method. It converts an array-like object to an array so that you can perform all the array operations on it.

Here the collection is an array:

collection

The Array.of() array method

The Array.of() method creates a new array using any number of elements of any type.

The output looks like this:

image-49

Array Iterator Methods in JavaScript

Now we're gonna learn about array iterator methods. These are very useful methods for iterating through array and performing computations, making decisions, filtering out stuff, and more.

So far, we have not seen an example of an array of objects. In this section, we will use the following array of objects to explain and demonstrate the methods below.

This array contains the information for some students subscribed to various paid courses:

Alright, let's get started. All the array iterator methods take a function as an argument. You need to specify the logic to iterate and apply in that function.

The filter() array method

The filter() method creates a new array with all the elements that satisfies the condition mentioned in the function. Let's find the student who is female. So the filter condition should be that the gender is equal to 'F'.

The output is this:

image-50

That's right. The student with name Rubi is the only female student we have got so far.

The map() array method

The map() method creates a new array by iterating through the elements and applying logic we provided in the function as an argument. We'll create a new array of full names of all the students in the students array.

image-51

Here we see a new array with the fullName properties that is computed using the f_name and l_name properties of each student object.

The reduce() array method

The reduce() method applies a reducer function on each of the array elements and returns an output value. We'll apply a reducer function on the students array to compute the total amount paid by all the students.

In the above code,

  • We initialize the accumulator with 0 .
  • We apply the reduce method on each of the student objects. We access the paid property and add it to the accumulator.
  • Finally, we return the accumulator.

The some() array method

The some() method returns a boolean value (true/false) based on at least one element in the array passing the condition in the function. Let's see if there are any students below the age 30.

Yes, we see there is at least one student younger than 30.

The find() array method

Using the some() method, we have seen that there is a student below age 30. Let's find out who that student is.

To do that, we will use the find() method. It returns the first matched element from the array that satisfies the condition in the function.

Arrays have another related method, findIndex() , that returns the index of the element we find using the find() method. If no elements match the condition, the findIndex() method returns -1 .

In the example below, we pass a function to the find() method that checks for the age of each of the student. It returns the matched student when the condition satisfies.

image-52

As we see, it is Alex who is 22 years old. We found him.

The every() array method

The every() method detects if every element of the array satisfies the condition passed in the function. Let's find if all the students have subscribed to at least two courses.

As expected, we see that the output is true .

Proposed Array Methods

As of May, 2021, ECMAScript has a method in proposal , the at() method.

The at() Method

The proposed at() method would help you access the elements of an array using a negative index number. As of now, this is not possible. You can access elements only from the beginning of the array using a positive index number.

Accessing elements from the back of the array is possible using the length value. With the inclusion of the at() method, you would be able to access the elements using both positive and negative indexes using a single method.

Here is a quick demo of it:

You can use this polyfill to achieve the functionality of the at() method until this method gets added to the JavaScript language. Please checkout this GitHub repository for the at() method examples: https://github.com/atapas/js-array-at-method

Before We End...

I hope you've found this article insightful, and that it helps you understand JavaScript arrays more clearly. Please practice the examples multiple times to get a good grip on them. You can find all the code examples in my GitHub repository .

Let's connect. You will find me active on Twitter (@tapasadhikary) . Please feel free to give a follow.

You may also like these articles:

  • Why do you need to know about Array-like Objects?
  • 5 useful tips about the JavaScript array sort method
  • Ways to Empty an Array in JavaScript and the Consequences
  • Build your JavaScript Muscles with map, reduce, filter and other array iterators
  • Why do you need to know about the JavaScript Array at() method?

Writer . YouTuber . Creator . Mentor

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

  • DSA with JS - Self Paced
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Operator
  • JS Projects
  • JS Cheat Sheet
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
  • JS Web Technology

Related Articles

  • Solve Coding Problems
  • How to execute TypeScript file using command line?
  • What is any type, and when to use it in TypeScript ?
  • What is the difference between interface and type in TypeScript ?
  • How to Import another TypeScript Files ?
  • Introduction to TypeScript
  • How to define an array of different generic types in TypeScript ?
  • How to implement class constants in TypeScript ?
  • How to compile a Typescript file ?
  • TypeScript Inheritance
  • How to check null and undefined in TypeScript ?
  • What is TypeScript Definition Manager and why do we need it ?
  • How to convert string to number in TypeScript ?
  • Explain the Tuple Types in TypeScript
  • Explain the purpose of never type in TypeScript
  • Explain when to use "declare" keyword in TypeScript
  • How to implement Inheritance in Typescript ?
  • How to check interface type in TypeScript ?
  • How tuple destructuring works in TypeScript ?
  • How to install TypeScript ?

How to Create Arrays of Generic Interfaces in TypeScript ?

In TypeScript , managing data structures effectively is crucial for building robust applications. Arrays of generic interfaces provide a powerful mechanism to handle varied data types while maintaining type safety and flexibility.

There are various methods for constructing arrays of generic interfaces which are as follows:

Table of Content

Using Array Generics

Using array mapping.

Arrays in TypeScript support generics , enabling the creation of arrays with elements of specific types, including interfaces. This approach offers a straightforward solution for organizing and manipulating data with predefined interface structures.

Example: Define an interface MyInterface with a generic type T, allowing for flexible data storage. The array myArray is declared with elements adhering to MyInterface<number>, ensuring each element maintains type consistency with the specified structure.

Array mapping offers a dynamic approach to transform existing arrays into arrays of generic interfaces. This method is particularly useful when dealing with data sources with diverse structures, allowing for seamless integration of interface definitions.

Example: In this example, we have an array existingArray containing items of type ItemType. By using array mapping, each item is transformed into a new object conforming to the interface structure defined by MyInterface, facilitating uniform data representation.

Please Login to comment...

author

  • Web Technologies

Improve your Coding Skills with Practice

 alt=

What kind of Experience do you want to share?

Chris Pietschmann is a Microsoft MVP, HashiCorp Ambassador, Microsoft Certified Trainer (MCT), Author, Trainer, Developer, DevOps / Site Reliability Engineer (SRE) with 20+ years of experience developing enterprise solutions. He has been focusing heavily on Microsoft Azure and the Cloud since early 2010, and specializes in DevOps / SRE, IoT, Development and Solution Architecture. He's the founder of Build5Nines.com , and works at Solliance as a Principal Cloud & DevOps Solution Architect.

Publications

  • Build5Nines.com
  • Hackster.io
  • Pietschsoft.com

Build5Nines.com Logo

JavaScript: Format Date to String

Sep 28, 2023  •  JavaScript

JavaScript provides a versatile Date object that allows you to work with dates and times. One common task you might encounter is formatting a JavaScript Date object as a string. This can be especially useful when you want to display a date in a specific format or when interacting with date-based APIs that require a particular date format.

In this article, we will explore how to format a JavaScript Date object into a custom string format. We’ll cover different aspects of date formatting and provide practical code examples to help you achieve this.

The Problem

The problem is clear: you have a JavaScript Date object, and you want to convert it into a string using a custom date format, similar to what you might do in other programming languages like C# or .NET.

For example, you might want to format a date like this:

From: Sat Sep 28 2023 14:30:00 GMT-0700 (Pacific Daylight Time)

To: 2023-09-28

The Solution

JavaScript doesn’t provide a built-in method to directly format a Date object with a custom string format like yyyy-MM-dd as in C#.

However, you can achieve this by following these steps:

  • Create a Date object: First, create a JavaScript Date object representing the date you want to format.
  • Define a formatting function: Create a function that takes the Date object and formats it according to your desired format. You can do this manually or use a library like date-fns or moment.js for more advanced formatting options.
  • Use the formatting function: Call the formatting function with your Date object as the argument to get the formatted date string.

Now, let’s see how you can do this with practical examples.

Example 1: A Formatting Function

To format a JavaScript Date to a string, you can write a custom function that does it so the code is reusable. Or, you can write a reusable function such as the one below that takes the Date object and a format string (like yyyy/MM/dd similar to that supported by C# / .NET date to string conversion) as inputs for how to format the Date as a string.

Here’s an example Date to String conversion function that takes such an input:

Then the usage of this function would be as follows:

Example 2: Using date-fns Library

Here, we use the date-fns library to format the Date object according to the specified format string (‘yyyy-MM-dd’).

Example 3: Using Intl.DateTimeFormat

In this example, we use Intl.DateTimeFormat to format the Date object based on locale-specific rules and options.

Formatting a JavaScript Date object as a string is a common task in web development. While JavaScript doesn’t provide a built-in method for this, you can achieve it easily by creating a custom formatting function or using libraries such as date-fns or Intl.DateTimeFormat . Choose the method that best suits your project’s requirements, and you’ll be able to format dates in JavaScript with ease.

How to Hide a Column in AG-Grid and Prevent it from Displaying in the Tool Panel

Javascript: loop through array (using foreach), javascript: parse a string to a date, javascript: how to convert map to an array of objects, check if element exists using javascript or jquery.

Build5Nines.com - Cloud & Enterprise Technology

Recent Posts

Javascript: how to print to console, console.log, console.error, console.debug, related posts, recent on build5nines.com.

NoSQL vs SQL: Demystifying NoSQL Databases

NoSQL vs SQL: Demystifying NoSQL Databases

Feb 5, 2024.

Some quick example text to build on the card title and make up the bulk of the card's content.

Terraform: Create Azure Cosmos DB Database and Container

Terraform: Create Azure Cosmos DB Database and Container

Nov 28, 2023.

Terraform: Deploy Azure App Service with Key Vault Secret Integration

Terraform: Deploy Azure App Service with Key Vault Secret Integration

Nov 17, 2023.

Workshop: Migrate RHEL Linux and MySQL Database to Azure

Workshop: Migrate RHEL Linux and MySQL Database to Azure

Oct 28, 2023.

Workshop: Migrate Windows Server and SQL Server to Azure

Workshop: Migrate Windows Server and SQL Server to Azure

Oct 26, 2023.

View all courses...

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Array.prototype.toString()

The toString() method of Array instances returns a string representing the specified array and its elements.

Return value

A string representing the elements of the array.

Description

The Array object overrides the toString method of Object . The toString method of arrays calls join() internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.prototype.toString is used instead, returning [object Array] .

JavaScript calls the toString method automatically when an array is to be represented as a text value or when an array is referred to in a string concatenation.

Array.prototype.toString recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString does not have delimiters, nested arrays look like they are flattened.

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

Using toString()

Using tostring() on sparse arrays.

Following the behavior of join() , toString() treats empty slots the same as undefined and produces an extra separator:

Calling toString() on non-array objects

toString() is generic . It expects this to have a join() method; or, failing that, uses Object.prototype.toString() instead.

Specifications

Browser compatibility.

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

  • Indexed collections guide
  • Array.prototype.join()
  • Array.prototype.toLocaleString()
  • TypedArray.prototype.toString()
  • String.prototype.toString()

IMAGES

  1. 5 Ways to Convert String to Array in JavaScript

    javascript create array of strings

  2. String Array in JavaScript

    javascript create array of strings

  3. How to turn a JavaScript string into an array

    javascript create array of strings

  4. JavaScript String Methods You Should Know

    javascript create array of strings

  5. 4 Ways to Convert String to Character Array in JavaScript

    javascript create array of strings

  6. JavaScript basic: Sort the strings of a given array of strings in the

    javascript create array of strings

VIDEO

  1. Javascript String and Array methods

  2. Converting an Array to string in JavaScript #javascript #webdevelopment #coding #programming

  3. strings || In JavaScript✨|| subscribe to @_with_srb for more content like this. #javascript

  4. Repeat( )

  5. String Methods in Javascript || Javascript 101 || Part 8

  6. 29

COMMENTS

  1. JavaScript Arrays

    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. Example const cars = ["Saab", "Volvo", "BMW"]; Try it Yourself »

  2. JavaScript generate array of strings with inline solution

    JavaScript generate array of strings with inline solution Ask Question Asked 6 years, 4 months ago Modified 6 years, 4 months ago Viewed 11k times 6 There simple code: var arr = []; for (var i = 0; i < 10; i++) { arr.push ("some string with iterating value "+i); }

  3. JavaScript Arrays

    May 16, 2022 / #JavaScript JavaScript Arrays - How to Create an Array in JavaScript Jessica Wilkins An array is a type of data structure where you can store an ordered list of elements. In this article, I will show you 3 ways you can create an array using JavaScript.

  4. Array() constructor

    Arrays can be created using a constructor with a single number parameter. An array is created with its length property set to that number, and the array elements are empty slots. js

  5. How to Convert a String to an Array in JavaScript

    // Splitstring using an empty string (on each character) let array2 = quote.split ( '' ); console .log (array2); // ["I", " ", "a", "m", " ", "u", "n", "s", "t", "o", "p", "p", "a", "b", "l", "e", "!"] // Split string using a specific character let array3 = quote.split ( 'p' ); console .log (array3); // ["I am unsto", "", "able!" ]

  6. How to Declare an Array in JavaScript

    There are two standard ways to declare an array in JavaScript. These are either via the array constructor or the literal notation. In case you are in a rush, here is what an array looks like declared both ways: // Using array constructor let array = new array("John Doe", 24, true); // Using the literal notation let array = ["John Doe", 24, true];

  7. Array

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

  8. JavaScript Basics

    To create a string you can use the String () constructor or a string literal. Here's an example of both ways: // Using a constructor let string1 = String('String Creation'); // Using a string literal let string2 = 'String Creation'; Now let's learn more about instance methods.

  9. How to create an array of strings in JavaScript?

    To create an array of strings in JavaScript, simply assign values − var animals = ["Time", "Money", "Work"]; You can also use the new keyword to create an array of strings in JavaScript − var animals = new Array ("Time", "Money", "Work"); The Array parameter is a list of strings or integers.

  10. Arrays

    Paste the following code into the console: js const shopping = ["bread", "milk", "cheese", "hummus", "noodles"]; console.log(shopping); In the above example, each item is a string, but in an array we can store various data types — strings, numbers, objects, and even other arrays.

  11. JavaScript Arrays

    Creating an Array using Array Constructor (JavaScript new Keyword) The "Array Constructor" refers to a method of creating arrays by invoking the Array constructor function. This approach allows for dynamic initialization and can be used to create arrays with a specified length or elements.

  12. How to Create Arrays in JavaScript

    Now there are a couple of ways to do this. Say that you want an array with three elements inside of it, we can pass it in just like this. var generatedArray = new Array ( 3 ); And this will create the array for us. If I say generatedArray now you can see that we have 3 items. They're all undefined.

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

  14. Array.from()

    Description. Array.from () lets you create Array s from: iterable objects (objects such as Map and Set ); or, if the object is not iterable, array-like objects (objects with a length property and indexed elements). To convert an ordinary object that's not iterable or array-like to an array (by enumerating its property keys, values, or both ...

  15. How to make an array from a string by newline in JavaScript?

    How to make an array from a string by newline in JavaScript? - Stack Overflow How to make an array from a string by newline in JavaScript? Ask Question Asked 10 years, 8 months ago Modified 2 years, 9 months ago Viewed 85k times 46 I've got this: var quoted_text = window.getSelection; For example: Accepting the Terms of Service

  16. Javascript dynamic array of strings

    Is there a way to create a dynamic array of strings on Javascript? What I mean is, on a page the user can enter one number or thirty numbers, then he/she presses the OK button and the next page shows the array in the same order as it was entered, one element at a time. Code is appreciated. javascript arrays Share Improve this question Follow

  17. How to Create Arrays of Generic Interfaces in TypeScript

    Syntax: interface MyInterface {. // Define interface properties/methods. } const myArray = existingArray.map ( (item: ItemType) => {. // Return transformed interface object. }); Example: In this example, we have an array existingArray containing items of type ItemType. By using array mapping, each item is transformed into a new object ...

  18. Array.prototype.join()

    The join () method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator. Try it Syntax js join() join(separator) Parameters separator Optional

  19. JavaScript: Format Date to String

    The Solution. JavaScript doesn't provide a built-in method to directly format a Date object with a custom string format like yyyy-MM-dd as in C#. However, you can achieve this by following these steps: Create a Date object: First, create a JavaScript Date object representing the date you want to format.

  20. Array.of()

    The Array.of () method is a generic factory method. For example, if a subclass of Array inherits the of () method, the inherited of () method will return new instances of the subclass instead of Array instances. In fact, the this value can be any constructor function that accepts a single argument representing the length of the new array, and ...

  21. javascript

    Is there an easy way to create an array of empty strings in javascript? Currently the only way I can think to do it is with a loop: var empty = new Array (someLength); for (var i=0;i<empty.length;i++) { empty [i] = ''; } but I'm wondering if there is some way to do this in one line using either regular javascript or coffeescript. javascript

  22. Array.prototype.toString()

    Description. The Array object overrides the toString method of Object. The toString method of arrays calls join () internally, which joins the array and returns one string containing each array element separated by commas. If the join method is unavailable or is not a function, Object.prototype.toString is used instead, returning [object Array].

  23. javascript

    1 Here's a solution in lodash that uses a combination of lodash#flatMapDeep and lodash#toPairs to get an array of keys and values that we can join using lodash#join. var array = [ {a: 1}, {b: 2}]; var result = _ (array).flatMapDeep (_.toPairs).join ('_'); console.log (result);