Arrays in JavaScript - introduction

ยท

7 min read

The Array is a type of object in JavaScript which allows us to store a collection of multiple items under a single variable name. You can consider it as a list of elements. Each items of the array are reffered to as elements and the position of the element in the array is known as index. Arrays start from the 0 index. Now lets look at an array.

// this is how an array looks in JavaScript
const arr=[0,1,2,3,4]
// you can also create an array like this
const arr=[]
const arr=new Array()

This is how you can access the elements of the array.

const arr=[1,2,3,4,5]
console.log(arr[0])// Output - 1
console.log(arr[4])// Output - 5

An array in Javascript doesn't have a fixed size and is not mandatory to store the elements of a particular type. Arrays can have elements of multiple datatypes.

const arr=["Hello",1,2.3,false,[1,2,3]]

It is possible but as you can see its difficult to manage so we dont do that.

There are lot of properties and methods that comes with the array object. To get the length of the array you can use the length property. This gives the number of elements present in the array.

const arr=[1,2,3]
console.log(arr.length)// Output - 3

How to add and remove elements from the array

To add element to an array you can use the push method and to remove element from the array you can use the pop method. But these two methods add elements at the end of the array and remove elements from the end of the array. But there are methods which perform the same operation at the start of the array. To insert element at the start use the unshift method and to remove an element from the start use the shift method. Here is an example. The unshift and the push method takes in the value to be inserted as the argument.

const arr = [0, 1, 2, 3, 4, 5]

//to insert element at end
arr.push(0)
console.log(arr)

//to delete element from the end
arr.pop()
console.log(arr)

//to insert element at the start
arr.unshift(0)
console.log(arr)

//to delete element from the start
arr.shift()
console.log(arr)

The output of the above code is as follows:

Some more methods

includes()

If you want to check if an element is present in the array or not, use the includes method. It returns true if the element is present and returns false if the element is not present.

const arr=[0,1,2,3,4,5]
console.log(arr.includes(3))// Output - true

.indexOf()

If the element is present and you want to get the index or position of the element in the array then use the indexOf method. It will return the index of the first occurence of the element, if present or it will return -1, if the element is not present.

const arr=[0,1,2,3,4,5]
console.log(arr.indexOf(1))

join()

This method lets you combine all the elements of an array and returns it as a single string.

const arr=[0,1,2,3,4]
const joined=arr.join()
console.log(joined)// Output - 0,1,2,3,4

You can even provide a custom separator as an argument to the join function.

const arr=[0,1,2,3,4]
const joined=arr.join('-')
console.log(joined)// Output - 0-1-2-3-4

As a result of this code the numbers in the array are joined together using a hyphen instead of default comma. You can even give a whitespace which will leave a blank space between the array elements in the string after they are joined.

split()

You can even split a string into an array. For that use the split method. This method takes in a string as an argument. Then the method will split the string into parts separated by the given string. Take a look at this code snippet.

const arr = [0,1,2,3,4]
const joined = arr.join()
const newArr = joined.split(',')
console.log(newArr)// Output - [0,1,2,3,4]

As we have previously seen what the join method does to an array. Now the joined is a string which has the value as 0,1,2,3,4. So now the split method has been passed an argument , which means it'll split the jonied string into parts separated by a comma or ,. So the answer will be the same as the original array arr.

These two methods are very important.

slice and splice

Suppose you want to get a segment or a part of the array on which you can perform some operations then you can use the slice or splice method. Both the element takes in two arguments the starting index and the ending index. But there are certain differences between the two methods and how they work. Lets looks into that.

const arr=[0,1,2,3,4,5]
const sliced = arr.slice(1,3)
console.log(`Original array: ${arr}, sliced array ${sliced}`)
const spliced = arr.splice(1,3)
console.log(`Original array: ${arr}, spliced array ${spliced}`)

Output of the above code snippet:

From the output you can observe two things. When you use the slice method the original array is not modiefied and a copy of the segment is returned and in case of the splice method orginal array is modified. Another thing is the slice method returns the element from the starting index to the element before the ending index passed as arguments to the method. Where as in case of the splice method the elements are returned from the starting index till ending index.

How to join two arrays

Using spread opeartor

Two join two arrays you can use the spread operator. The spread operator spreads the array elements into each individual elements and then puts it into the array.

const arr = [1, 2, 3, 4, 5]
const secArr = [6, 7, 8]
const spreadArr = [...arr, ...secArr]
console.log(`using spread operator: ${spreadArr}`)//output - [1,2,3,4,5,6,7,8]

conact()

To join two arrays you can use the concat() method. This method returns a new array after joining or concatinating the two arrays.

const arr = [1, 2, 3, 4, 5]
const secArr = [6, 7, 8]
// using concat method, returns a new array
const concatedArr = arr.concat(secArr)
console.log(`using concat: ${concatedArr}`)
//output - [1,2,3,4,5,6,7,8]

How to create new array out of values

Lets say you are given a string and you will have to create a new array out of each characters of that string. How will you do that, you can use the Array.from() method for that. This method takes in a string as argument and returns an array, which contains each character of the string as an element in the array.

const toArray = Array.from("javascript")
console.log(toArray)
// Output - ['j', 'a', 'v', 'a', 's', 'c', 'r', 'i', 'p', 't']

Now this method can be also used over objects as well, but there you will also have to mention wether you want to extract the key strings as an array or the values. check out the docs for more details, take it as a homework from me ๐Ÿ˜‰

But how will you check if a given value is already an array or not. For that use the Array.isArray() method. This method returns true if its an array or false if its not.

console.log(Array.isArray("javascript"))// Output - false

Now we learned how to create an array out of all the characters present in a string, then lets checkout how can we create an array out of some values that we have. This is how you would do that. Oh! wait for that we'll be using Array.of() method.

let a = 10
let b = 20
let c = 30
const abc = Array.of(a, b, c)
console.log(abc)

So this method takes in all the values that you give it and creates a new array including all the elements and returns it.

So thats most of the things that comes to my mind when I think of array and its methods and properties, this is enough to know as a beginner. Are there no more methods other than these? No, definetly not. There are other methods as well. You must explore them from the docs and try them out. Its always the best to look and the docs. Now most of the develpoers might argue, hey you didn't mentioned the forEach method and how to iterate an array, yeah I know because its an introductory blog on arrays in javascript and there will be more blogs in future. Where I'll dive deep and raise the bar.

Ok so that's all you need to know and keep in your subconscious mind. Now I hope working with arrays in JavaScript will be a breeze for you. Thank me later or give your feedbacks on what you think about this introductory blog on arrays in javascript. If you like coding content like this then you can follow my Youtube channel and facebook page , there I upload videos on tech and coding realted stuffs. Till then have a good day and keep coding!

ย