Post navigation

Coding

JavaScript Array and Usage

An array is one of the main and basic concepts of JS. It is an essential part of any programming language. You can play with a Javascript array like whatever you want. This is a powerful tool used in javascript. However, there are some major differences in Javascript and other languages. It is very essential to figure out the concept of an array and its use in JS.

On other hands, an array is nothing but the collection of the elements access by a single variable in the javascript. Most importantly a global object used to the creation of the array i.e. list like objects.

Declaration of Javascript Array

There are many places you can use arrays. You also declare an array as following with exmaples


# Declaration Of Array
var ref = [];
var ref = new Array();

# Example
var ref = ["one","two","three"]
var ref = new Array("one","two","three")

Detect Array

In Javascript, there is one classic problem to determine whether a given object is an array or not. instanceof will check if the type is an array.


# Detect Array

if (ref instanceof Array) {
  // do some array stuff 
}

Length of the Array

Its very efficient to check if an array is filled or empty. However, this seems odd but highly effective property. Most importantly, it will return the value of index+1. Simply, it gives the length of the array.


# Measure the length
var ref = ["one","tow","three"]
console.log(ref.length) 

Traversing an array

Traversing an array is simple and you can use for each loop. it is simple and fast way to traverse. For each loop requires a callback functions as an argument.


var array1 = ['a', 'b', 'c'];

array1.forEach(function(element) {
  //logic goes here
  console.log(element);
});

// output: "a"
// output: "b"
// output: "c"

But you can simply breck forEach() loop by throwing exception.

Map Property

A map is a method which requires a callback function as an argument which it will execute for each element in the array but with results of callback function it creates a new array.


var array1 = [1, 4, 9, 16];

// pass a function to map
var sq = array1.map(function(x){
	return x * x
})

console.log(sq);
// output: Array [1, 16, 81, 256]

Filter in Array

The filter() method creates a new array with all elements. And that pass the conditions implemented in the provided callback function.


var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(function(word){
    return word.length > 6
});

console.log(result);
// output: Array ["exuberant", "destruction", "present"]

However, If no elements pass the conditions in function, an empty array will be returned.

Find Property

The find() method returns the value of the first element in the array that satisfies the provided conditions in the callback function. Otherwise undefined is returned.


var array1 = [5, 12, 8, 130, 44];

var found = array1.find(function(element) {
  return element > 10;
});

console.log(found);

// output: 12

Find Index Property

This method is almost the same as Array.find method above except
findIndex() method returns the index of the first element in the array that satisfies the provided conditions in the callback function. Otherwise, it returns -1, indicating no element passed the conditions.


// Find Index in array

var array1 = [5, 12, 8, 130, 44];

function isLargeNumber(element) {
  return element > 13;
}

console.log(array1.findIndex(isLargeNumber));

// output: 3

Every Property

The every() method tests whether all elements in the array meets the conditions implemented by the provided function. That is that every element in array satisfies the conditions , return type of this function is boolean either true or false


//Check For Even Number

function isEven(element) {
  return element % 2 == 0;
}

var array1 = [1, 30, 40, 51, 10, 2];

console.log(array1.every(isEven));

//output: false


//Check For Even Number

function isEven(element) {
  return element % 2 == 0;
}

var array1 = [4, 16, 18, 22, 30];

console.log(array1.every(isEven));

// output: true

However, this method or property returns true for any condition put on an empty array.

Array.some() Property

In logic, this function is the opposite of every function because some() method tests whether at least one element in the array satisfies the conditions implemented by the provided function. Unlike every() where all elements must meet the provided conditions, in some if even one element meets the condition function returns true. A return type of this method is boolean either true or false.


function isEven(element) {
  return element % 2 == 0;
}

var array1 = [1, 30, 40, 51, 10, 2];

console.log(array1.some(isEven));

//output: true

Concat in Array

The concat() method or property is used to merge two or more arrays in JS. This method does not change the existing array. But instead returns a new array. In the concat method, the original array is not modified but a new array is a return as methods result. And any operation on newly return array wont affect the original arrays from which it was made.


var array_first = ['a', 'b', 'c'];
var array_second = ['d', 'e', 'f'];

console.log(array_first.concat(array_second));

// output: Array ["a", "b", "c", "d", "e", "f"]

Join method

The join() property creates and returns a new string by concatenating all of the elements. The join methods take the separator as a parameter by default string separated by commas. Also, it specified separator strings given as a parameter to join function. If any element is undefined or null, it is converted to the empty string.


var elements = ['Fire', 'Wind', 'Rain'];

console.log(elements.join());

// output: "Fire,Wind,Rain"

console.log(elements.join(''));

// output: "FireWindRain"

console.log(elements.join('-'));

// output: "Fire-Wind-Rain"

Includes Property

The includes() method determines whether an array includes a certain value among its entries. Which is returning true or false as appropriate.


var array1 = [1, 2, 3];

console.log(array1.includes(2));

// output: true

var pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));

// output: true

console.log(pets.includes('at'));

// output: false

But, when you comparing strings and characters, includes() is case-sensitive.

Furthermore, Javascript arrays are always zero indexed. So, it starts with zero indexes when you initialized it. You can later add value in it.

To sum up, these array methods are very helpful when you understand the JS language. Therefore, as a JS developer, you must have the knowledge to use it properly. I hope you will see this information useful.

Also read,

Keep Coding.

Spread the love
  • 5
  •  
  •  
  •  
  • 1
  •  
  •  
  •  
  •  
Siddhant Sankhe

About Siddhant Sankhe