An in-depth look at Arrays

Prakash Pawar
Webtips
Published in
5 min readAug 7, 2018

Hey i am Prakash and today we are going to talk about arrays. In javascript one has to consider mastering Arrays, Variables, Loops, and Objects in their beginning phase. Today we are going to Discuss about arrays and their properties and methods but before i start with Methods and properties of Array, let me ask you a simple question what is an array and how you can define an array?

“Underwater view of a man snorkeling in Lembongan Island.” by Jeremy Bishop on Unsplash

Array

The JavaScript Array object is a global object that is used in the construction of arrays, which are high level list-like objects(According to MDN)

In simple words, suppose array is a bus, empty seats are indexes starts from 0. So the question is what is on the seats? the answer is little wired if you ask me, seats could be any possible values in JavaScript.

Let's take an Example of an Array:

//creating an array with few different types values
var arr=[1,'two',{three:3},{fo:{ur:true}}];
//accessing arr using bracket notation
arr[0];//1
arr[1];//'two'
arr[2];//{three: 3}
arr[3];//{fo: {ur:true}}
//accessing array with bracket and dot notation
arr[3].fo.ur;//true

In the above example you can see that we can put any primitive type values or even nested object type of value inside an array without any errors, but what about functions? we will check them later in this post.

Copying Array

At the beginning of learning, we have to sync our brain with codes and for starting this process we have to go with easy methods.

Before I start with methods lets make a copy of our previous array.

//how to not make a copy of an arrayvar newArr0= arr;//❌ Wrong Way of referencingvar newArr1= Array.from(arr);//✔️ right way of referencing

In the above example if you are copying an array into a new variable using first way(wrong way) it will create problems while you do modification in the new array.

//❌ Wrong Way assigning/referencing 
var fruits=["apple", "orange", "graphs"];
//assigning to new array
var mixFruits= fruits;
mixFruits.push('cashew');//4
//check mixFruits and fruits now
console.log(mixFruits);//(4) ["apple", "orange", "graphs", "cashew"]
console.log(fruits);//(4) ["apple", "orange", "graphs", "cashew"]

Above we can see how a wrong way of copying can ruin all your effort. Now, let's start with methods. First, let's talk about four absolute beginner methods that everyone should understand in there beginners phase.

Four Beginner Methods

push() & pop()

As names suggest push() and Pop() are used to add or remove values from an array. Push() adds value at the end of the array and Pop() removes values from the same end.

//lets take an array of superheroes
var superHeroes=['batman','superman'];
//let push/add a new hero in the end of an array
superHeroes.push('ironman');
//check superhero array again
console.log(superHeroes);//['batman','superman','ironman']
//but ironman belongs to marvel , lets remove him
superHeroes.pop();//pop doesn't take any arguments
//check our array again
console.log(superHeroes);//['batman','superman']

unshift() and shift()

These two unshift() and shift() works the same as push() and pop() but for the front-end of the array. These methods are very handy while working on really messy projects.

//again lets take an array of superwomen
var superWomen=['black widow', 'captain marvel'];
//let unshift/add a new superwoman in the front of an array
superWomen.unshift(’wonderwoman’);
//check superwomen array again
console.log(superWomen);
//['wonderwoman','black widow', 'captain marvel']
//but wonderwoman belongs to dc, lets remove her
superWomen.shift();//pop doesn't take any arguments
//check our array again
console.log(superWomen);//['black widow', 'captain marvel']

now you know how to add or remove a value in array from both the side, let's talk about 3 nuke level methods for an array that is strong enough to replace for loops in many cases.

Three Nuke Methods

“Think like we have an array of sandwich ingredients , filter() method will filter out the ingredient we don’t like to eat and map() method will iterate over all the ingredient and chop them for us and finally reduce() method will build sandwich using them.” ( quote by @anjanavakil.)

map()

map() method never modifies an original array instead it returns a new array with some tweaks. map() method iterates each and every value in an array, applies a callback function and gets back a new modified version of an original array, think like map() is taking raw food and cooking it for us in lesser code without using for loop.

Let's take an Example

//map method on numbers
//squaring the number
let arrNumber = [2,4,5];
let arrSquare = arrNumber.map((num)=> {return num* 2});//using map()
console.log( arrSquare );//(3) [4, 8, 10]
//map method on strings
let arrString=['hi', 'Hello', 'Namaste'];
let arrString2= arrString.map(str => str.toUpperCase());
//using map() and uppercase() method
console.log( arrString2 ); //(3) ["HI", "HELLO", "NAMASTE"]

filter()

Suppose we have a water purifier and it has filter() method implemented with a callback function. That function takes only boolean values( true or false). If Array value is true it will return it to us, if Array value is false it won’t return. In purifiers filter(), the callback function gives bacterias a false value and removing them and gives purified water a true value and returning them to us. In simple words filter() works like this way, the value is either true or false, and if any value doesn’t qualify, callback function test filter() skips those values.

Let's take an Example

//filter method to get only strings
let myValues =[1,5,'hey', 'grow', true, false, true,{value:5}];
let newValues= myValues.filter((obj)=> typeof(obj) === "string");
console.log( newValues );//["hey", "grow"]
//filter method to get only positive numbers
let numbers=[ -1,-4,-6,0,9,55,30];
let newNumber= numbers.filter(num => num >= 0);
//this will return only positive numbers with 0
console.log(newNumber);//(4) [0, 9, 55, 30]

reduce()

reduce() method is the most powerful in this set of three and most complicated to understand. In reduce() method we have to pass two parameters first a callback function and second is an initial value for accumulator, the callback function has two parameters an accumulator( initial value holder) and current value. The callback function gets executed multiple times for each value of array and process it with accumulator.

let's take an Example

//reduce method act as a filter method
//biggest no. in array list
let num= [2,6,77,33,20,84,53,43];//apply reduce
let bigNum= num.reduce((acc,curr)=>{
if(acc>curr){return acc}
else{return curr}}
);
console.log(bigNum);//84
//and if you want to check how does it work
let bigNum2= num.reduce((acc,curr)=>{
console.log(acc,curr);
if(acc>curr){return acc}
else{return curr}});
console.log(bigNum2);//try it yourself

Alright, this is it, a beginner level explanation of Arrays in JavaScript, and if you like this article you can join me on twitter.

I will write an intermediate level post on arrays in JavaScript level soon, till then please give your valuable feedback via claps and comments.

--

--

Prakash Pawar
Webtips
Writer for

Curious to learn about universe and beyond. Learning Web Development.