Arrays, Function and String in JavaScript
JavaScript Arrays and Strings – Complete Guide
In this tutorial, we will learn about two important JavaScript concepts: Arrays and Strings. We will cover array creation, indexing, array methods, loops, multidimensional arrays, string traversal, searching, slicing, replacing, and type conversion.
📚 Table of Contents
1. JavaScript Arrays
An array is an ordered collection of elements used to store multiple values in a single variable.
Creating an Empty Array
There are two common syntaxes for creating an empty array:
let arr = [];
let arr = new Array();
The first syntax, [], is generally preferred for creating
arrays.
Creating an Array with Values
let fruits = ["Pineapple", "Mango", "Watermelon"];
2. Array Indexing
Array elements are ordered and their index starts from 0.
let fruits = ["Pineapple", "Mango", "Watermelon"];
document.write(fruits[0]);
document.write(fruits[1]);
document.write(fruits[2]);
| Index | Value |
|---|---|
| 0 | Pineapple |
| 1 | Mango |
| 2 | Watermelon |
Replacing Array Values
We can replace an array value by assigning a new value to its index.
fruits[1] = "Guava";
The above statement replaces Mango with Guava.
Adding an Element
fruits[3] = "Orange";
This adds Orange at index 3.
Finding Array Length
document.write(fruits.length);
The length property returns the number of elements in an array.
3. JavaScript Array Methods
JavaScript provides several useful methods for adding and removing elements from arrays.
| Method | Purpose | Position |
|---|---|---|
| push() | Adds element(s) | End |
| pop() | Removes element | End |
| shift() | Removes element | Beginning |
| unshift() | Adds element(s) | Beginning |
pop()
The pop() method removes the last element from an array
and returns the removed element.
let fruits = ["Apple", "Orange", "Pear"];
document.write(fruits.pop());
document.write(fruits);
push()
The push() method adds one or more elements to the end
of an array.
let fruits = ["Apple", "Orange"];
fruits.push("Mango");
document.write(fruits);
Output:
Apple, Orange, Mango
shift()
The shift() method removes the first element from an array.
let fruits = ["Apple", "Orange", "Mango"];
document.write(fruits.shift());
document.write(fruits);
The first element Apple is removed.
unshift()
The unshift() method adds one or more elements at the
beginning of an array.
let fruits = ["Orange", "Mango"];
fruits.unshift("Apple");
document.write(fruits);
Output:
Apple, Orange, Mango
Adding Multiple Elements
let fruits = ["Apple"];
fruits.push("Orange", "Guava");
fruits.unshift("Pineapple", "Mango");
document.write(fruits);
Result:
["Pineapple", "Mango", "Apple", "Orange", "Guava"]
4. Traversing an Array
Traversing means visiting each element of an array one by one. JavaScript provides several ways to traverse an array.
Using for Loop
let arr = ["Apple", "Orange", "Pear"];
for (let i = 0; i < arr.length; i++) {
document.write(arr[i]);
}
Using for...of
The for...of loop directly gives us the values of an array.
let fruits = ["Apple", "Orange", "Plum"];
for (let fruit of fruits) {
document.write(fruit);
}
Using for...in
The for...in loop gives the index/property keys.
let arr = ["Apple", "Orange", "Pear"];
for (let key in arr) {
document.write(arr[key]);
}
for...of
or a traditional for loop is generally clearer than
for...in.
5. Using new Array()
Another way to create an array is by using the Array
constructor.
let arr = new Array("Apple", "Mango", "Orange");
Important: new Array(number)
If new Array() receives a single numeric argument, that
number represents the array's length rather than an element.
let arr = new Array(2);
document.write(arr[0]);
document.write(arr.length);
The first statement attempts to access an element that has not been
assigned, so the result is undefined. The array length is
2.
6. Multidimensional Arrays
A multidimensional array is an array that contains other arrays. A two-dimensional array can be visualized as rows and columns.
Method 1: Creating Inner Arrays First
let arr1 = ["Ajay", 24, 18000];
let arr2 = ["Mayur", 30, 30000];
let arr3 = ["Mehak", 28, 41000];
let arr4 = ["Rajni", 31, 28000];
let arr5 = ["Yuvraj", 29, 35000];
let salary = [arr1, arr2, arr3, arr4, arr5];
Method 2: Directly Creating a 2D Array
let salary = [
["Ajay", 24, 18000],
["Mayur", 30, 30000],
["Mehak", 28, 41000],
["Rajni", 31, 28000]
];
Here, the array contains 4 rows and each row contains 3 values.
Accessing a Multidimensional Array
for (let i = 0; i < salary.length; i++) {
for (let j = 0; j < salary[i].length; j++) {
document.write(salary[i][j]);
}
}
The first index selects the row and the second index selects the element within that row.
salary[0][0] // Ajay
salary[0][1] // 24
salary[0][2] // 18000
7. JavaScript Strings
A string is a sequence of characters used to represent textual data. JavaScript does not have a separate data type for a single character; a single character is also represented as a string.
Three Ways to Create Strings
1. Double Quotes
let str = "Welcome to Program";
2. Single Quotes
let str = 'Welcome to Program';
3. Backticks
let str = `Welcome to Program`;
${...}.
8. Traversing a String
Since strings are sequences of characters, individual characters can be accessed using their index.
Using Index
let str = "Welcome to Program";
document.write(str[3]);
The character at index 3 is c.
Using charAt()
let str = "Welcome to Program";
document.write(str.charAt(5));
The character at index 5 is m.
9. Important String Methods
1. Changing String Case
The toUpperCase() method converts a string to uppercase,
while toLowerCase() converts it to lowercase.
let str = "programming in javascript";
let upper = str.toUpperCase();
document.write(upper);
let str1 = "PROGRAM OF JAVASCRIPT";
let lower = str1.toLowerCase();
document.write(lower);
2. Searching Using indexOf()
The indexOf() method searches for a substring and returns
its starting index. If the substring is not found, it returns
-1.
let str = "Welcome to JavaScript Program";
document.write(str.indexOf("Welcome"));
document.write(str.indexOf("welcome"));
document.write(str.indexOf("Program"));
indexOf() is case-sensitive.
Therefore, "Welcome" and "welcome" are treated
as different strings.
Searching from a Specific Position
str.indexOf("Program", 10);
3. slice()
The slice() method extracts part of a string. The ending
index is not included.
let str = "JavaScript Program";
document.write(str.slice(0, 5));
Output:
JavaS
If the end index is omitted, the string is extracted from the starting position to the end.
document.write(str.slice(4));
4. substring()
The substring() method is similar to slice().
One useful difference is that if the first index is greater than the
second index, JavaScript swaps the two values.
let str = "JavaScript Program";
document.write(str.substring(0, 5));
document.write(str.substring(5, 0));
Both statements produce the same substring.
5. substr()
The older substr() method takes a starting index and a
number of characters.
let str = "JavaScript Program";
document.write(str.substr(3, 6));
substr() is
deprecated. For new code, prefer slice() or
substring().
6. Converting a Number to String
The toString() method can convert a number into a string.
let value = 2000;
let str = value.toString();
document.write(str);
7. Converting a String to Number
The parseInt() function can convert a numeric string into
an integer.
let str = "2000";
let value = parseInt(str);
document.write(value);
parseFloat()
can be used. For general numeric conversion,
Number() is also commonly used.
8. Replacing Text Using replace()
The replace() method returns a new string with a specified
portion replaced. It does not modify the original string.
let str = "Welcome to JavaScript Program";
let result = str.replace("Program", "Language");
document.write(result);
Output:
Welcome to JavaScript Language
Case-Insensitive Replacement
A regular expression with the i flag can be used for a
case-insensitive replacement.
let str = "Welcome to JavaScript Program";
let result = str.replace(/program/i, "Language");
document.write(result);
Replacing All Occurrences
The g flag can be used with a regular expression to replace
all matching occurrences.
let str =
"Sumit is a good athlete, Sumit runs very fast, Sumit covers 100 meter distance in 9 seconds";
let result = str.replace(/Sumit/g, "Raghav");
document.write(result);
Result:
Raghav is a good athlete, Raghav runs very fast, Raghav covers 100 meter distance in 9 seconds
10. Quick Revision
| Method / Property | Purpose |
|---|---|
| length | Returns the number of elements/characters |
| push() | Adds elements at the end of an array |
| pop() | Removes the last element |
| shift() | Removes the first element |
| unshift() | Adds elements at the beginning |
| charAt() | Returns character at an index |
| indexOf() | Searches for a substring |
| slice() | Extracts part of a string |
| substring() | Extracts part of a string |
| toUpperCase() | Converts string to uppercase |
| toLowerCase() | Converts string to lowercase |
| replace() | Replaces matching text |
| toString() | Converts a value to string |
| parseInt() | Converts a string to an integer |
Comments
Post a Comment