Object in Javascript explained

This is a detailed article on what the Javascript object is and how prototype works in a real browser. Each and every object holds two basic characteristics: methods and properties. You will learn the difference between the properties of an object and normal Javascript variables and how methods and normal Javascript function differ from each other. Well, you find them in detail within this post.

How many types of objects are there in JavaScript?

JavaScript has an Object data type, which is a complex one, and has five simple data types, which are: String, Number, Boolean, Undefined, and Null. Note that these simple (primitive) data types cannot be changed (immutable) while on the other hand, objects can be changed (mutable).

What are built in objects in JavaScript?

These objects are Math, Date, Array, String, and Object, as some other languages have. but JavaScript has a different implementation of them.

Object declaration best practices:

  • Defining an object property using brackets [] is an older method try using dot (.) syntax instead.
  • The use of ‘ new object()’ is an older approach, instead use { }.
  • The jQuery objects are auto generated and only accessed by jQuery methods, therefore sometimes using them with native JS causes problems, but not all of them, like length property. So Don’t confuse with it
  • Objects are accessible via for…in loop in Javascript. This loop only iterates enumerable properties of an object.

A basic example where dot syntax doesn’t work, but bracket syntax works is when a property name is based on numbers and not the string.

It is the association which makes a difference between native Javascript function and an object’s method. A function is independent of any object and can be triggered without associating with any object while a method is called with an association to an object.

var mData={}; // An object

// Adding the method
myData.mName=function(e){
  console.log("My name is "+e);
}
// Running the method
myData.mName('David');

// A function
 function mName(e){
   console.log("My name is "+e);
 }
// Running function
mName('David Peter');

// Logs
My name is David
My name is David Peter

The same difference holds by a normal variable and object’s property and that are associated. But keep in mind that things are not that simple as they seem. A front end application can cause a big blunt in the codes if object’s method and properties are not used in a definite way.

Assume a Javascript environment which has many objects. Using of `this` keyword can cause the application to return wrong or maybe `undefined` values while running a method, as every page has a window object which is the parent object present. Executing a method outside the specific object perspective will target the window as a primary object. This misleading is not mentioned in many tutorials, describing the Javascript’s object oriented behavior. So, for this reason, as described above, we use call, bind and apply method.

var baby = {
  name: 'William',
  age: '1 year'
}
// Creating a local baby object below
var hospital = {
  baby: {
    name: 'Tom',
    age: '2 year'
  },
  getBaby: function(e) {
      console.log('This is ' + this.baby.name + ' and he is ' + this.baby.age + ' old')
    }
}
var currentBaby = hospital.getBaby;
currentBaby(); // This is William and he is 1 year old

The above example demonstrates how small errors could lead to a break down. The solution to this problem is to use other methods available.

Object property attributes

Every object property contains its own attributes which actually change our way of dealing with them. There are actually 3 types of attributes, each data set contains.

1. Enumerable

This attribute is true for all defined properties, but not for the one inherited. Enumerable properties are those who iterate in for… in the loop so if any property is set to non-enumerable then we won’t see them in the loop. Like length property is non-enumerable since it is an inherited property.

To test the property, we use obj.propertyIsEnumerable() that returns a Boolean value. Like length or toSting() will return false while user defined properties will return true.

var car = {
  name: 'Benz'
};
console.log(car.propertyIsEnumerable('toString')); // false
console.log(car.propertyIsEnumerable('name')); // true

2. Writable

All those properties which can be edited using JS syntax are known as writable. Once the object is said to non-writable, then object’s value is no longer changeable unless redefined using object.defineProperty()

3. Configurable

Those properties which can be deleted using `delete` syntax are simply configurable. If they are said to `false` using object.defineProperty() then they become non-configurable.

object.defineProperty()
This builtin method allows you to create an object’s property by not only setting values, but also setting the attributes which will define the working of the object.

var car={name:'Benz'}
Object.defineProperty(car,'model',{
  value:'r8',
  writable:false,
  enumerable:true,
  configurable:true
})
console.log(car.model) // r8
car.model='r10';
console.log(car.model) // r8

You might not be aware of this method of changing the property’s attribute. It’s a very nice way to work with objects.

Reference variable and property

Now reference of the variable to another variable might not be surprising if we go through a simple example like this one.

var car='Benz';
var updateCar=car;
car='BMW';
console.log(updateCar); // Benz
console.log(car); // BMW

After updating the variable, the referenced variable did not have an effect because it is the nature of the variable, but the object property does not show the same existence.

var car={myCar:'Benz'};
var updateCar=car;
car.myCar='BMW';
console.log(updateCar.myCar); // Benz
console.log(car.myCar); // BMW

You can also see that updating the property of the object changes the referenced variable as well.

Objects in array

This is a common condition when objects are placed in arrays. Consider an array containing more than 1 object. Now, maybe all objects have the same properties and different values or different properties. In order to get the value of the choosing, it is necessary to use loops to handle them as we do with the normal array.

var kids = [{
  name: 'Thomas',
  age: '12'
}, {
  name: 'Peter',
  age: '8'
}, {
  name: 'William',
  age: '5',
  youngest: true
}];

function getKids(e) {
  for (var i = 0; i < e.length; i++) {
    var kid = e[i];
    console.log(kid.name);
  }
}

function getYoung(e) {
  for (var i = 0; i < e.length; i++) {
    var kid = e[i];
    if (kid.youngest) {
      console.log('Yougest Kid is:' + kid.name);
    }
  }
}
getKids(kids);
// Thomas
// Peter
// William
getYoung(kids);
// William

Well, the discussion about the use of jQuery’s each method vs the use of the’ for’ loop is worth addressing right here. If you’ve ever thought of using the $.each method instead of the’ for’ loop just for easy coding, make sure that jQuery’s $.each method is much slower than the’ for’ loop. The image below is taken from the stackoverflow .

$().each vs. $.each vs. jQuery loop?
The reason is that jQuery $.each method is best suited to working with objects that I think are the worst part of it because jQuery objects are too slow in performance, and each jQuery object creation takes time. Therefore, Lea Verou’s post must be worth reading before using jQuery for large projects.

Add a Comment

Your email address will not be published. Required fields are marked *

Enjoy best web development services at an affordable price. Looking forward to build a good relationship and serve you better...

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote