Arrays & it's method in JavaScript
Table of contents
What's an Array
An array is a special type of variable, which can store multiple values using special syntax. Every value is associated with numeric index starting with 0. Square brackets[ ] are used to declare/represent an Array. JavaScript arrays are resizable and can contain a mix of different data types.
Array Initialization
In JavaScript an array can be defined and initialized in two ways, array literal and Array constructor syntax.
Array Literal
const mixed = ["india", "shubh", "march", 24, true]; // mixed is declared and initialized
const midarr = ["navee", 23, false, 24, true]; // midarr is declared and initialized
console.log(mixed); //for displaying array on console
output:
Array Constructor
const newarr = new Array("a", "bb", true);
console.log(newarr);
output:
Array Properties
length
Array includes "length" property which returns number of elements in the array.
//declaration and initialization of array
const stringArray = ["one", "two", "three", "four"];
let arrayLength = stringArray.length; //value of array length assigned to arrayLength variable
console.log(arrayLength); //displaying arrayLength
output:
Array Methods
Array.isArray()
Array.isArray() method checks whether the given value is an array or not. It returns true if value is an array else false.
const array1 = [2, 4, 6, 8, 10];
console.log(`Is it an array: ${Array.isArray(array1)}`);
let fName = "CoursesOnline";
console.log(`Is it an array: ${Array.isArray(fName)}`);
output:
at()
The at() method takes an integer value and returns the item at that index, allowing for positive and negative integers. Negative integers count back from the last item in the array.
const array1 = [5, 12, 8, 130, 44];
console.log(`the item returned is ${array1.at(2)}`);
console.log(`the item returned is ${array1.at(-2)}`);
output:
concat()
Returns the new array after joining/merging two or more arrays or arrays values.Not modify the original array, it will give new array.
const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3);
output:
copyWithin()
The copyWithin() method shallow copies part of an array to another location in the same array and returns it without modifying its length, but it modifies the original array.
Syntax:
array.copyWithin(target_index, start_index, end_index)
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(arr.copyWithin(1, 5, 7));
output:
every()
every() method returns true/false boolean value. It returns true if, all the elements in the array pass the test implemented by the function passed as an argument.
//Syntax:
//array.every(function_ref);
function checkOdd (num){
return num % 2 != 0
}
const nums = [1, 5, 7, 9]
console.log(nums.every(checkOdd)) // true
const num2 = [2, 1, 3, 11]
console.log(num2.every(checkOdd)) // false
output:
fill()
The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified array.
// syntax
// array.fill(value_to_fill, start_index, end_index )
const array1 = [2, 4, 6, 8];
// fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// fill 6 in entire array
console.log(array1.fill(6));
output:
filter()
filter( ) method filters out the elements from the array that pass the condition provided in the function
const words = ['shubh', 'exile', 'elite', 'protection', 'future', 'lenght'];
const result = words.filter(word => word.length > 6);
console.log(result);
output:
find()
find() method returns the first element from the array that satisfies the condition provided in the function. If no element satisfies the condition then, undefined is returned.
const array1 = [3, 9, 4, 6, 11, 8];
const result = array1.find( num => num % 2 == 0);
console.log(result);
output:
findIndex()
findIndex( ) method returns the index of the first element from the array that satisfies the condition provided in the function. If no element satisfies the condition then, -1 is returned.
const array1 = [3, 9, 4, 6, 11];
const result = array1.findIndex( num => num % 2 == 0);
console.log(result);
output:
forEach()
The forEach() method executes a provided function once for each array element.
const array1 = ["hey", "hello", "hola"];
array1.forEach((val) => {
console.log(val);
});
output:
includes()
The includes() method checks whether the value you are searching is inside the array at the index you specify. It returns true or false.
//Syntax
//array.includes(value_to_check, index_where_to_check);
const array1 = [2, 4, 6, 8, 10];
let result = array1.includes(6, 2);
let result1 = array1.includes(6, 3);
console.log(result);
console.log(result1);
output:
indexOf()
Checks the index position of the element of array. Returns the first index at which a given element can be found in the array, or -1 if it is not present.
const array1 = [2, 4, 6, 8, 10, 4, 2];
let result = array1.indexOf(4);
console.log(result);
output:
lastIndexOf()
lastIndexOf( ) method returns the last index position at which value is present in the given array or, returns -1 if value is not present.
const array1 = [10, 2, 10, 8, 4, 6, 8, 10, 6];
let result = array1.lastIndexOf(10);
console.log(result);
output:
join()
The join() method creates and returns a new string by concatenating all of the elements in an array, separated by commas or a specified separator string.
const elements = [ 'Rise', 'Roar', 'Revolt', 'Movie' ];
console.log(elements.join());
console.log(elements.join('-'));
output:
map()
The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = [1, 4, 9, 16, 25];
const result = array1.map(Math.sqrt);
console.log(result);
output:
pop()
The pop() method removes the last element from an array and returns that element. This method modifies the length of the original array.
const array1 = ["jaipur", "delhi", "mumbai", "agra", "goa"];
console.log(array1.pop());
console.log(array1);
output:
push()
The push() method adds one or more elements to the end of an array and thus modifies the length of the original array.
const array1 = ["jaipur", "delhi", "mumbai"];
console.log(array1.push("agra"));
console.log(array1);
output:
reverse()
The reverse() method reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. This method changes the original array.
const array1 = ['one', 'two', 'three', 'four'];
console.log('original array:', array1);
const reversed = array1.reverse();
console.log('reversed array:', reversed);
// modifies original array
console.log('array1:', array1);
output:
shift()
The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
const array1 = ['one', 'two', 'three', 'four'];
const shiftarr = array1.shift();
console.log('shifted element:', shiftarr);
// modifies original array
console.log('updated array1:', array1);
output:
unshift()
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
const array1 = ['one', 'two', 'three',];
console.log('orginal array:', array1);
array1.unshift("zero");
console.log('unshift array:', array1);
output:
slice()
The slice() method returns a shallow copy of a portion of an array into a new array. The original array will not be modified.
//Syntax
// array.slice(start_index, end_index);
const array = [2, 4, 6, 8, 10, 12];
const newarr = array.slice(2, 5);
console.log(newarr);
output:
splice()
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
//Syntax
// array.slice(index, how_many_values_to_delete, new_values);
const array = [2, 4, 6, 8];
console.log(array);
array.splice(1, 0, 8, 10);
console.log(array);
output:
sort()
The sort() method sorts the elements of an array in place and thus modifies the original array.
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
output:
split()
The split() method converts the string into array.
let str = "Array";
const array1 = str.split('');
console.log(array1);
output:
toString()
The toString() method returns a string representing the specified array and its elements.
const array1 = [1, 2, 'abc', '2xyz'];
console.log(array1.toString());
output:
Thanks for reading and I hope you had a good learning experience. Any Feedback and Suggestions are highly welcomed.
#iwritecode
Subscribe to my newsletter
Read articles from Shubham Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Shubham Singh
Shubham Singh
I am a Computer science graduate and passionate frontend web developer and I design and code beautifully simple things, and I love what I do.I like to code things from scratch, and enjoy bringing ideas to life in the browser.Currently on journey of learning Full Stack Javascript Development