If you are using JavaScript often or frequently in your development, so you likely used arrays many times and you may consider it as one of the javascript data types, don’t be shocked but actually this not true!
1- What is the data types in JavaScript?
JavaScript has two types of data types, Primitive datatypes and Complex data types
Primitive data types is String, Number, Boolean, Undefined and Function
Any other data types is belong to Object data type!
2- What is the origin of Arrays!?
if we have an array and trying to now it’s type you might think of using the keyword typeof
var users=['John','Joe','Sandy']; typeof users //output: Object
So what is the origin of arrays. Arrays is an inherited prototype from the type ‘Object’
3- What is the inheritance in JavaScript?
Although JavaScript doesn’t support standard OOP, but we code simulate a base class using the function declaration like the following
function Car(model,color,year){ this.model=model||'BMW'; this.color=color||'Black'; this.year=year||1970; }
“this” keyword here refers to any instance will be created from the class Car using “new” keyword
var car = new Car('BMW','blcak',1990);
Now let’s add some methods to this class using ‘prototype’ property which define all methods can be used with our Car data type i.e any new instances created from Car class. this the same as you use ‘length’ prototype property which retrieving the number of elements for any array
Car.prototype.incrementYear=function(){ ++this.year; };
Now let’s create a child class named ChildCar which inherit from Car
function ChildCar(model,color,year){ Car.apply(this,[model,color,year]); } ChildCar.prototype=Car.prototype; //inherit Car prototype ChildCar.prototype.changeModel=function(model){ this.model=model; } var newChild = new ChildCar("Ferarri","blue",2017);
Now we can use the method “incrementYear” on the instance newChild but we can’t use the method “changeModel” on the instance “car”
newChild.incrementYear(); console.log(newChild.year) //2018
but how should we now the type of the newChild? we have to use instanceof
typeof car // Object typeof newChild // Object car instanceof Car //true newChild instanceof Car //true newChild instanceof ChildCar //true car instanceof ChildCar //false
So Array is …
Arrays is an inherited prototype of object via new class called Array so we can check of this like
var users=['John','Joe','Sandy']; typeof users //output: Object users instanceof Array //true