JavaScript Array: From Basics to Advanced

You are currently viewing JavaScript Array: From Basics to Advanced
Array

What is Array and what are the different methods to create/declare the array?

An array is a special variable, which can hold more than one value in a single variable.

Methods to Create/Declare Arrays

const original = [1, 2, 3];
const copy = [...original];
//Output[1, 2, 3]

const array2 = [..."JavaScript"];
console.log(array2);
//['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
Method NameDescriptionExample
Array Literal NotationThe most common way to create an array using square brackets [].const arr = [1, 2, 3, 4, 5];
Array ConstructorCreates an array using the Array constructor.
Can be used to create arrays with a specified length or with elements.
//Empty Array
const arr1 = new Array();
//Array with a Specific Length:
const arr2 = new Array(5);
//_____________________________________
//Array with Specific Elements:
const arr3 = new Array(1, 2, 3, 4, 5);
Array.of()Creates a new Array instance with a variable number of arguments.
const arr = Array.of(1, 2, 3, 4, 5);
console.log(arr)
//output[1, 2, 3, 4, 5]
Array.from()Creates a new Array instance from an array-like or iterable object.
const str = 'hello';
const chars = Array.from(str); 
//output['h', 'e', 'l', 'l', 'o']
Spread OperatorExpands an array into its individual elements or converts an iterable into an array.
const original = [1, 2, 3];
const copy = [...original];
//Output[1, 2, 3]

const array2 = [..."JavaScript"];
console.log(array2);
//['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']
Array.fill()Creates an array with a specific length and fills it with a specified value.
const myArray= new Array(4).fill(5);
console.log(myArray);
// output [5, 5, 5, 5]
Methods to Create/Declare Arrays

Can you summarizing the most basic and commonly used array methods in JavaScript?

Here’s a table summarizing some of the most basic and commonly used array methods in JavaScript, including their descriptions and examples:

NameDescriptionExample
Array.lengthProperty that returns the number of elements in an array.
const arr = [1, 2, 3];
console.log(arr.length)
//output 3
Array.push()Adds one or more elements to the end of an array and returns the new length of the array.
const arr = [1, 2, 3];
arr.push(4);
console.log(arr)
//output [1, 2, 3, 4]
arr.push(5,6);
console.log(arr)
//output [1, 2, 3, 4, 5, 6]
Array.pop()Removes the last element from an array and returns that element.
const arr = [1, 2, 3];
let el = arr.pop();
console.log(el);// output 3
console.log(arr);//output [1, 2]
Array.shift()Removes the first element from an array and returns that element.
const arr = [1, 2, 3];
let el = arr.shift();
console.log(el);// output 1
console.log(arr);//output[2, 3]
Array.unshift()Adds one or more elements to the beginning of an array and returns the new length of the array.
const arr = [1, 2, 3];
arr.unshift(4);
console.log(arr)
//output [4, 1, 2, 3]
arr.unshift(5,6);
console.log(arr)
//output [5, 6, 4, 1, 2, 3]
Array.concat()Combines or merge two or more arrays and returns a new array.
const arr1 = [1, 2]; 
const arr2 = [3, 4];
const result = arr1.concat(arr2);
console.log(result);
//output [1, 2, 3, 4]
const result2 = arr1.concat(arr2).concat(["A","B"]);
console.log(result);
//output [1, 2, 3, 4, 'A', 'B']
Array.join()Joins all elements of an array into a string, separated by a specified delimiter.
const array = ['AA', 'BB', 'CC'];
console.log(array.join());// Output: "AA,BB,CC"
console.log(array.join(' - ')); // Output: "AA - BB - CC"
Array.toString()Used to convert an array to a string.
const array = [1, 2, 3, 4];
const stringRepresentation = array.toString();
console.log(stringRepresentation); // "1,2,3,4"
Array.splice()used for modifying an array by adding or removing elements. It directly alters the original array and returns an array of removed elements (if any).

Removing Elements

const fruits = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
// Remove 2 elements starting from index 1
const removed = fruits.splice(1, 2);
console.log(removed); // Output: ['banana', 'cherry']
console.log(fruits);  // Output: ['apple', 'date', 'elderberry']

Adding Elements

const fruits = ['apple', 'banana', 'cherry'];

// Add 'kiwi' and 'mango' at index 1
const removed = fruits.splice(1, 0, 'kiwi', 'mango');
console.log(removed); // Output: [] (no elements removed)
console.log(fruits);  // Output: ['apple', 'kiwi', 'mango', 'banana', 'cherry']

Replacing Elements

const fruits = ['apple', 'banana', 'cherry', 'date'];
// Replace 2 elements starting from index 1 with 'kiwi' and 'mango'
const removed = fruits.splice(1, 2, 'kiwi', 'mango');
console.log(removed); // Output: ['banana', 'cherry']
console.log(fruits);  // Output: ['apple', 'kiwi', 'mango', 'date']
Array.slice()Create a shallow copy of a portion of an array into a new array object. It does not modify the original array but rather returns a new array containing the selected elements.
array.slice(start, end)
start: Start position. Default is 0.
end: End position. Default is last element.
const fruits = ['apple', 'banana', 'cherry', 'date'];

// Extract elements from index 1 to 3 (excluding index 3)
const slicedFruits = fruits.slice(1, 3);
console.log(slicedFruits); // Output: ['banana', 'cherry']
const slicedFruits2 = fruits.slice(2);
console.log(slicedFruits2 ); // Output: ['cherry', 'date']
console.log(fruits);
 // Output: ['apple', 'banana', 'cherry', 'date'] (original array unchanged)
Array.forEach()Used for iterating over arrays and performing actions on each element.
const fruits = ['apple', 'banana', 'cherry'];

fruits.forEach(function(fruit, index,_ary) {
  console.log(index, fruit,_ary);
});

/* output
0, 'apple', ['apple', 'banana', 'cherry']
1, 'banana', ['apple', 'banana', 'cherry']
2, 'cherry', ['apple', 'banana', 'cherry']
*/
Array.map()Creates a new array by applying a function to each element of an existing array.
const numbers1 = [1, 2, 3, 4, 5];
const numbers2 = numbers1.map(function(value, index, array) {
  return value * index;
});
console.log(numbers2);
// Output: [0, 2, 6, 12, 20]
//------------------------------
const numbers = [1, 2, 3, 4, 5];
const squares = numbers.map(num => num * num);
console.log(squares);
// Output: [1, 4, 9, 16, 25]

//-------Extracting Property Values
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];
const names = users.map(user => user.name);
console.log(names);
// Output: ['Alice', 'Bob', 'Charlie']
Array.filter()Creates a new array with all elements that pass the test implemented by the provided function. It is useful for filtering elements based on certain conditions.
const numbers = [4, 12, 19, 5, 8, 21];
const greaterThanTen = numbers.filter(function(value, index, array) {
  return value > 10;
});
console.log(greaterThanTen);
// Output: [12, 19, 21]

//--Filtering Active Users
const users = [
  { name: 'Alice', isActive: true },
  { name: 'Bob', isActive: false },
  { name: 'Charlie', isActive: true }
];
const activeUsers = users.filter(user => user.isActive);
console.log(activeUsers);
// Output: [
//   { name: 'Alice', isActive: true },
//   { name: 'Charlie', isActive: true }
// ]

//---Filtering Even Numbers
const numbers1 = [1, 2, 3, 4, 5, 6];
const evenNumbers = numbers1.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6]
Array.find() and Array.findLast()Returns the first element in the array that satisfies the provided testing function.

The Array.findLast() Returns the value of the last element in an array that pass a test
const numbers = [4, 12, 19, 5, 8, 21];
const firstGreaterThanTen = numbers.find(function(num, index, array) {
  return num > 10;
});
console.log(firstGreaterThanTen); // Output: 12
const LastGreaterThanTen = numbers.findLast(function(num, index, array) {
  return num > 10;
});
console.log(LastGreaterThanTen ); // Output: 21

Finding an Object by Property

const users = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
];
const userWithId2 = users.find(user => user.id === 2);
console.log(userWithId2);
// Output: { id: 2, name: 'Bob', age: 30 }
Array.findIndex() and
Array.findLastIndex()
Returns the index of the first element in the array that satisfies the provided testing function.

The Array.findLastIndex() Returns the index of the last element in an array that pass a test.
const numbers = [4, 12, 19, 5, 8, 21];
const index  = numbers.findIndex(function(num, index, array) {
  return num > 10;
});
console.log(index ); // Output: 1
const lastIndex  = numbers.findLastIndex(function(num, index, array) {
  return num > 10;
});
console.log(lastIndex ); // Output: 5
//---Finding an Index by Property
const users = [
  { id: 1, name: 'Alice', age: 25 },
  { id: 2, name: 'Bob', age: 30 },
  { id: 3, name: 'Charlie', age: 35 }
];
const userIndexWithId2 = users.findIndex(user => user.id === 2);
console.log(userIndexWithId2);
// Output: 1
Array.sort()Sorts the elements of an array in place and returns the array.
The default sorting order is according to string Unicode code points
const numbers = [10, 5, 100, 50];
numbers.sort();
console.log(numbers);// Output is [10, 100, 5, 50]

numbers.sort(function(a, b) {
  return a - b; // For ascending order
});
console.log(numbers);// Output is [5, 10, 50, 100]

Array with String elements

const fruits = ['banana', 'apple', 'cherry'];
fruits.sort(); // Default sort is alphabetical
console.log(fruits); // Output: ['apple', 'banana', 'cherry']

Sorting Objects by a Property

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];
people.sort(function(a, b) {
  return a.age - b.age; // Sort by age
});
console.log(people);
/*Output: [
  { name: 'Bob', age: 25 },
  { name: 'Alice', age: 30 },
  { name: 'Charlie', age: 35 }
]*/
Array.reverse()Reverses the elements of an array in place and returns the array.
const numbers = [1, 2, 3, 4, 5];
numbers.reverse();
console.log(numbers); // Output: [5, 4, 3, 2, 1]

Reversing a String Array

const fruits = ['apple', 'banana', 'cherry'];
fruits.reverse();
console.log(fruits); // Output: ['cherry', 'banana', 'apple']

Reversing an Array of Objects

const people = [
  { name: 'Alice', age: 30 },
  { name: 'Bob', age: 25 },
  { name: 'Charlie', age: 35 }
];
people.reverse();

console.log(people);
/*Output: [
  { name: 'Charlie', age: 35 },
  { name: 'Bob', age: 25 },
  { name: 'Alice', age: 30 }
]*/
Array.copyWithin()Copies a portion of an array to another location within the same array, without modifying its size. It allows you to replace part of the array with a copy of another part of the same array.
array.copyWithin(target, start, end)
const numbers = [1, 2, 3, 4, 5];
numbers.copyWithin(0, 3, 5);
console.log(numbers); // Output: [4, 5, 3, 4, 5]
//-----------
const arr = [10, 20, 30, 40, 50];
arr.copyWithin(1, 3);
console.log(arr); // Output: [10, 40, 50, 40, 50]
Array.entries()returns a new Array Iterator object that contains the key/value pairs for each index in the array.
const array = ['a', 'b', 'c'];
const iterator = array.entries();
for (let entry of iterator) {
  console.log(entry);
}
/*Output
[0, 'a']
[1, 'b']
[2, 'c'] */
Array.every()Tests whether all elements in an array pass a provided test function. It returns a Boolean value (true or false),
const numbers = [1, 2, 3, 4, 5];
const allPositive = numbers.every(function(num) {
  return num > 0;
});

console.log(allPositive); // Output: true
Array.fill()Fill all or part of an array with a static value, from a start index to an end index. This method modifies the original array and returns the updated array.
array.fill(value, start, end)
const array = [1, 2, 3, 4, 5];
array.fill(0);
console.log(array); // Output: [0, 0, 0, 0, 0]
array.fill(9, 1, 4);
console.log(array);// Output: [0, 9, 9, 9, 0]

const arrayObj = new Array(3);
arrayObj.fill({ name: 'JavaScript' });
/* 
Output: 
[{ name: 'JavaScript' }, { name: 'JavaScript' }, { name: 'JavaScript' }]
 */
Array.flat()Used to flatten nested arrays. It creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
let arr = [1, [2, 3], [4, [5, 6]]];
let flatArr = arr.flat();
console.log(flatArr); // Output: [1, 2, 3, 4, [5, 6]]
////------Depth 2
let arr1 = [1, [2, [3, [4]]]];
let flatArr = arr1.flat(2);
console.log(flatArr); // Output: [1, 2, 3, [4]]

//-------Infinity
let arr2 = [1, [2, [3, [4, [5]]]]];
let flatArr = arr2.flat(Infinity);
console.log(flatArr); // Output: [1, 2, 3, 4, 5]
Array.from()Create a new array instance from an array-like or iterable object. This method provides a way to convert various types of objects into arrays. It also allows you to transform the elements of the array using a mapping function.
Array.from(object, mapFunction, thisValue)
let str = 'hello';
let arr = Array.from(str, function(char) {
    return char.toUpperCase();
});
console.log(arr); // Output: ['H', 'E', 'L', 'L', 'O'] 

Convert a NodeList (array-like object) to an array

let nodeList = document.querySelectorAll('div');
let arrayFromNodeList = Array.from(nodeList);
console.log(arrayFromNodeList); // Output: Array of div elements

Converting a Set or Map to an Array

let mySet = new Set([1, 2, 3, 4]);
let arrayFromSet = Array.from(mySet);
console.log(arrayFromSet); // Output: [1, 2, 3, 4]

let myMap = new Map([['a', 1], ['b', 2]]);
let arrayFromMap = Array.from(myMap);
console.log(arrayFromMap); // Output: [['a', 1], ['b', 2]]
Array.includes()Determines whether an array includes a certain element.
array.includes(valueToFind, fromIndex);
let numbers = [1, 2, 3, 4, 5];
console.log(numbers.includes(3)); // Output: true
console.log(numbers.includes(6)); // Output: false

let fruits = ['apple', 'banana', 'cherry'];
console.log(fruits.includes('banana', 1)); // Output: true
console.log(fruits.includes('banana', 2)); // Output: false
Array.indexOf()Search the array for an element and returns its position
array.indexOf(searchElement, fromIndex);
let numbers = [10, 20, 30, 40, 50];
console.log(numbers.indexOf(30)); // Output: 2
console.log(numbers.indexOf(100)); // Output: -1

let fruits = ['apple', 'banana', 'cherry', 'banana'];
console.log(fruits.indexOf('banana')); // Output: 1
console.log(fruits.indexOf('banana', 2)); // Output: 3
Array.reduce()Reduce the values of an array processes each element of an array to reduce it to a single value, using a function that updates an accumulator. (going left-to-right)
//Sum of All Elements
const numbers = [1, 2, 3, 4, 5];
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
console.log(sum); // Output: 15
Array.reduceRight()The Array.reduceRight() method in JavaScript works similarly to Array.reduce(), but it processes the array elements from right to left instead of left to right.
const arrays = [[1, 2], [3, 4], [5, 6]];
const concatenated = arrays.reduceRight((accumulator, currentValue) => {
  return accumulator.concat(currentValue);
}, []);

console.log(concatenated); // Output: [5, 6, 3, 4, 1, 2]
Array.some()Tests whether at least one element in the array passes the test implemented by the provided function.
const numbers = [1, 2, 3, 4, 5];
const hasEvenNumber = numbers.some(num => num % 2 === 0);
console.log(hasEvenNumber); // Output: true
//------------
const people = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];
const hasTeenager = people.some(person => person.age < 20);
console.log(hasTeenager); // Output: false
Array.toReversed()Array.toReversed() method is a new method introduced in ECMAScript 2024 that returns a new array with the elements in reverse order without modifying the original array.
const numbers = [1, 2, 3, 4, 5];
const reversedNumbers = numbers.toReversed();

console.log(reversedNumbers); // Output: [5, 4, 3, 2, 1]
console.log(numbers);         // Output: [1, 2, 3, 4, 5] 
Array.with()The Array.with() method is a new addition to JavaScript introduced in ECMAScript 2024. It provides a way to create a new array with one or more elements replaced at specified indices, without modifying the original array.
const numbers = [1, 2, 3, 4, 5];
const newNumbers = numbers.with(2, 99);

console.log(newNumbers); // Output: [1, 2, 99, 4, 5]
console.log(numbers);   // Output: [1, 2, 3, 4, 5] (original array remains unchanged)
Array Methods

How to Count Element Occurrences from Array?

To count the occurrences of elements in an array, we can use the Array.reduce() method. Here’s a simple way to do it:

const array = ['apple', 'banana', 'apple', 'orange', 'banana', 'banana'];
const countOccurrences = array.reduce((accumulator, item) => {
  // If the item is already a key in the accumulator object, increment its count
  if (accumulator[item]) {
    accumulator[item]++;
  } else {
    // Otherwise, add the item to the accumulator with a count of 1
    accumulator[item] = 1;
  }
  return accumulator;
}, {});
console.log(countOccurrences);
// Output: { apple: 2, banana: 3, orange: 1 }

How to check object/variable type is Array?

There are four methods to check if a variable is an array in JavaScript.

Methods to check ArrayCode
Array.isArray()
const arr = [1, 2, 3];
const obj = { key: 'value' };
console.log(Array.isArray(arr)); // Output: true
console.log(Array.isArray(obj)); // Output: false
instanceof Operator
const arr = [1, 2, 3];
const obj = { key: 'value' };
console.log(arr instanceof Array); // Output: true
console.log(obj instanceof Array); // Output: false
Object.prototype.toString.call()
const arr = [1, 2, 3];
const obj = { key: 'value' };

function isArray(value) {
  return Object.prototype.toString.call(value) === '[object Array]';
}

console.log(isArray(arr)); // Output: true
console.log(isArray(obj)); // Output: false
constructor Property
const arr = [1, 2, 3];
const obj = { key: 'value' };

console.log(arr.constructor === Array); // Output: true
console.log(obj.constructor === Array); // Output: false

How do you find min and max values without Math functions?

You can also find the minimum and maximum values in an array by sorting the array and then accessing the first and last elements. Here’s how you can do it without using Math.min() or Math.max() functions, but with the Array.sort() method.

function findMinMaxUsingSort(arr) {
  if (arr.length === 0) {
    throw new Error('Array cannot be empty');
  }

  // Copy the array to avoid mutating the original
  const sortedArray = arr.slice().sort((a, b) => a - b);

  const min = sortedArray[0];
  const max = sortedArray[sortedArray.length - 1];

  return { min, max };
}

// Example usage
const numbers = [5, 3, 9, 1, 6];
const { min, max } = findMinMaxUsingSort(numbers);

console.log('Min:', min); // Output: Min: 1
console.log('Max:', max); // Output: Max: 9

What is the difference between slice and splice?

Featureslice()splice()
PurposeCreates a shallow copy of a portion of the array.Adds or removes items from the array in place.
Original ArrayUnchangedModified
Return ValueA new array with the extracted elements.An array of removed elements.
Parametersstart (optional), end (optional)start, deleteCount (optional), items (optional)
ModificationDoes not modify the original array.Modifies the original array.
Usage Examplearray.slice(1, 3)array.splice(1, 2, 'new1', 'new2')
Deep CopyCreates a shallow copy (not deep).No copy, modifies the array directly.
difference between slice and splice

What does it mean when slice() creates a shallow copy (not a deep copy)?

When we say that Array.slice() creates a “shallow copy” of an array, it means that the new array created by slice() is a new array instance, but the elements inside the new array are not themselves copied deeply. Instead, they are references to the same objects that are in the original array. This distinction is important for understanding how slice() handles objects and nested arrays.

Example 1: Shallow Copy with Primitives


const original = [1, 2, 3];
const copied = original.slice();
console.log(copied);//    Output: [1, 2, 3]
copied[0] = 99;
console.log(original); // Output: [1, 2, 3] (original array remains unchanged)
console.log(copied);  //  Output: [99, 2, 3]

Example 2: Shallow Copy with Objects

const original = [{ name: 'Alice' }, { name: 'Bob' }];
const copied = original.slice();

console.log(copied); // Output:   [{ name: 'Alice' }, { name: 'Bob' }]

copied[0].name = 'Charlie';
console.log(original); // Output: [{ name: 'Charlie' }, { name: 'Bob' }]
console.log(copied);   // Output: [{ name: 'Charlie' }, { name: 'Bob' }]

What is destructuring assignment?

Destructuring assignment is a syntax in JavaScript that allows you to keyphrase unpack values from arrays or properties from objects into distinct variables. It provides a concise and readable way to extract data from arrays and objects.

const numbers = [1, 2, 3, 4];
const [first, second, third] = numbers;

console.log(first);  // Output: 1
console.log(second); // Output: 2
console.log(third); // Output: 3
//-----------Object 
const person = {
  name: 'Alice',
  age: 30,
  job: 'Engineer'
};
const { name, age, job } = person;

console.log(name); // Output: Alice
console.log(age);  // Output: 30
console.log(job);  // Output: Engineer
//-----------nested Object------
const user = {
  name: 'Bob',
  address: {
    street: '123 Main St',
    city: 'Somewhere'
  }
};

// Nested object destructuring
const { name, address: { street, city } } = user;

console.log(name);   // Output: Bob
console.log(street); // Output: 123 Main St
console.log(city);   // Output: Somewhere

const [a = 1, b = 2,c = 6] = [3,5];
console.log(a); // Output: 3
console.log(b); // Output: 5
console.log(c); // Output: 6 default value

How do you swap variables in destructuring assignment?

let a = 5;
let b = 10;
// Swap the values of a and b
[a, b] = [b, a];
console.log(a); // Output: 10
console.log(b); // Output: 5

What will be the Output […”JavaScript”]?

The spread operator (...) to convert a string into an array of its individual characters.

console.log([..."JavaScript"]); 
// Output: ['J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't']

How do you remove falsy values from an array?

//Using filter
const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.filter(Boolean);
console.log(filteredArray);
// Output: [1, 2, 3, 4, 5]

//Using reduce
const reduceArray = array.reduce((acc, item) => {
  if (item) acc.push(item);
  return acc;
}, []);
console.log(reduceArray );

How can you obtain unique values from an array?

const array = [1, 2, 2, 3, 4, 4, 5];
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
// Output: [1, 2, 3, 4, 5]

// Using reduce and includes
const uniqueArray1 = array.reduce((accumulator, value) => {
  if (!accumulator.includes(value)) {
    accumulator.push(value);
  }
  return accumulator;
}, []);
console.log(uniqueArray1 );
// Output: [1, 2, 3, 4, 5]

How do you empty an array?

//1. Setting Length to 0
let array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array); // Output: []
//2. Using splice() Method
let array = [1, 2, 3, 4, 5];
array.splice(0, array.length);
console.log(array); // Output: []
//3. Reassigning to an Empty Array
let array = [1, 2, 3, 4, 5];
array = [];
console.log(array); // Output: []

What will happen if you either set an array’s length property to 0 or reassign the array variable to an empty array ([])?

Scenario 1: Setting length to 0: The original array is emptied, and all references to it (including myObj.arry_ref) will reflect this change.

let myArray = [1, 2, 3, 4, 5];
let myObj = { array_ref: myArray };
myArray.length = 0;
console.log(myArray);//Output []
console.log(myObj);  //Output {array_ref: []}

Scenario2: Reassigning the Array Variable []: The myArray variable is assigned a new empty array, but myObj.arry_ref continues to point to the original array, which remains unchanged.

It creates a new array, so if other parts of your code hold references to the original array, they will not see this change.

let myArray = [1, 2, 3, 4, 5];
let myObj = { array_ref: myArray };
myArray = [];
console.log(myArray);//Output []
console.log(myObj);  //Output { array_ref: [1,2,3,4,5]}

What methods have the same name for both arrays and strings in JavaScript, and how do they differ?

Method/PropertyDescriptionArray ExampleString Example
lengthReturns the number of elements or characters.let arr = [1, 2, 3]; console.log(arr.length); // 3let str = "hello"; console.log(str.length); // 5
concatCombines multiple arrays or strings into one.let arr1 = [1, 2]; let arr2 = [3, 4]; console.log(arr1.concat(arr2)); // [1, 2, 3, 4]let str1 = "hello"; let str2 = "world"; console.log(str1.concat(" ", str2)); // "hello world"
sliceExtracts a portion of the array or string.let arr = [1, 2, 3, 4]; console.log(arr.slice(1, 3)); // [2, 3]let str = "hello world"; console.log(str.slice(0, 5)); // "hello"
indexOfFinds the index of the first occurrence of an element or substring.let arr = [1, 2, 3]; console.log(arr.indexOf(2)); // 1let str = "hello world"; console.log(str.indexOf("world")); // 6
lastIndexOfFinds the index of the last occurrence of an element or substring.let arr = [1, 2, 3, 2]; console.log(arr.lastIndexOf(2)); // 3let str = "hello world world"; console.log(str.lastIndexOf("world")); // 12
includesChecks if an array contains a certain element or if a string contains a substring.let arr = [1, 2, 3]; console.log(arr.includes(2)); // truelet str = "hello world"; console.log(str.includes("world")); // true
toStringConverts the array or string to a string.let arr = [1, 2, 3]; console.log(arr.toString()); // "1,2,3"let str = "hello"; console.log(str.toString()); // "hello"
reverseReverses the order of elements or characters.let arr = [1, 2, 3]; console.log(arr.reverse()); // [3, 2, 1]let str = "hello"; console.log(str.split("").reverse().join("")); // "olleh"
Arrays and strings in JavaScript

To more about the JavaScript String, Click here.

You can share it on

Leave a Reply