Initialize a string array in JavaScript
This post will discuss how to initialize a string array in JavaScript.
There are several ways to initialize a string array in JavaScript, depending on the syntax used. Here are some of the methods that we can use, along with some examples:
1. Using an array literal
This is the simplest and most common way to create a string array in JavaScript. We just use a pair of square brackets to enclose a comma-separated list of string values. It is simple and concise, and it is a common practice to declare arrays with the const keyword to avoid being reassigned to a different value. Here’s an example:
|
1 2 3 4 |
// an array of 3 strings const arr = new Array("apple", "banana", "cherry"); console.log(arr); |
In this example, arr is a string array that contains three elements: "apple", "banana", and "cherry".
2. Using Array constructor
The Array constructor is another way to initialize a string array in JavaScript, but it is less concise and less preferred than the array literal function. We use the new keyword and the Array() constructor function to create an array object with the string values as arguments. It is equivalent to using the array literal notation, but it may be less readable and more verbose. Here’s an example of how we can achieve this:
|
1 2 3 4 |
// an array of 3 strings const arr = new Array('apple', 'banana', 'cherry'); console.log(arr); |
We can also initialize an array with a fixed length using the Array() constructor as follows. In this example, arr is a string array with a length of 3 containing elements "apple", "banana", and "cherry".
|
1 2 3 4 5 6 |
const arr = new Array(3); arr[0] = "apple"; arr[1] = "banana"; arr[2] = "cherry"; console.log(arr); |
3. Using Array.of() function
The Array.of() is a built-in function that can create an array from a variable number of arguments. If the arguments are strings, it creates a string array. However, this requires ES6 support or a polyfill for older browsers. Here’s an example:
|
1 2 3 4 |
// an array of 3 strings const arr = Array.of("apple", "banana", "cherry"); console.log(arr); |
4. Using Array.from() function
The Array.from() is another built-in function that can create an array from an iterable or an array-like object. If the object is a string, it creates a string array using its characters. This function also requires ES6 support or a polyfill for older browsers. Here’s an example:
|
1 2 3 4 5 6 7 |
// a string let str = "Hello"; // an array of 5 strings: ["H", "e", "l", "l", "o"] const arr = Array.from(str); console.log(arr); |
That’s all about initializing a string array in JavaScript.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)