Object in JavaScript

Home / Object in JavaScript

Object in JavaScript

December 9, 2015 | Article | No Comments

JavaScript has object. We have cover it a bit and compactly, now we will discuss it deeper.

JavaScript object can be view as two different system. One, we can see object as an associative array (aka hash). It stores key-value pairs. On the other side, objects are used for object-oriented programming, using dot notation to access properties and method.

In modern day, JavaScript object also used as a data format known as JSON (Java Script Object Notation). However that is beyond our scope. We will only speak about JavaScript Object, like it is.

Objects, See in Simple Way

Objects in JavaScript, in many ways, are like objects in the real world (world outside programming language). Technically, we model them. In the real world, an object is just a “thing” or noun: a car, a table, a chair, a bottle.

Every objects have:

  • Properties (analogous to adjectives): The car is black.
  • Methods (like verbs in sentence): The car can be started, by turning ignition key.
  • Events: turning the ignition key results in the car starting.

Object-oriented programming (OOP) tries to make programming easier by modelling real-world objects. Let’s say we were creating a car simulator. First, you create a car object, giving it properties like colorand current speed. Then we need to create methods: perhaps a startmethod to start the car, and a brakemethod to slow the car, into which we need to pass information about how hard the brakes should be pressed so that you can determine the slowing effect. Finally, you would want to know when something happens with your car. In OOP, this is called an event. For example, when the gas tank is low, the car sends a notification (that light on the dashboard) letting us know it’s time to fill up. In this code, you would want to listen for such an event so that you can do something about it.

Now, unlike real object-oriented programming language, JavaScript doesn’t dive to deep. We have no interest in complex matter such as inheritance, polymorphism, etc. We just need object in simple way.

Creating Object

An empty object (you may also read as empty associative array) can be created with one of two syntaxes:

o = new Object()
o = { }

The values will be stored as key-value pair. The “properties” can be assigned or delete using “dot notation”. Unlike static type like C++, we can add or delete properties / method dynamically at need.

var obj = { }           // create empty object
obj.name = 'Xathrya';   // add entry with key 'name' and value 'Xathrya'

alert(obj.name);        // get value by key 'name'

delete obj.name;

We can also use brackets instead of dot. The key is passed as a string.

var obj = { }             // create empty object
obj['name'] = 'Xathrya';  // add entry with key 'name' and value 'Xathrya'

alert(obj['name']);       // get value by key 'name'

delete obj['name'];

Both give same result.

We can also declare an object type, like any OOP language. It is actually a group of key-value pairs. The key-value pairs will act as properties and/or method, enclosed by curly-bracket and written as list separated by comma. The key-value pair is written separated by : (colon) operator. For example:

objectLiteral

Which in turn:

var menuSetup = {
    width: 300,
    height: 200,
    title: "Menu"
}

// same as:

var menuSetup = { }
menuSetup.width = 300;
menuSetup.height = 200;
menuSEtup.title = 'Menu';

It is also possible to create nested object:

var user = {
    name: "Xathrya",
    id: 13510,
    birthdate: {
        day: 27,
        month: 9,
        year: 1991
    }
}

alert(user.name);          // "Xathrya"
akert(user.birthdate.day); // 27

Non-Existing Properties

We know that we can fetch property from an object. But if the property does not exist, then undefined is returned. It is the sign for us that the indicated property is undefined, or not exist.

var obj = { }

var value = obj.nonexistant;

alert(value);

So, to check whether the value is defined, we can use following:

if (obj.name !== undefined) {   // strict comparison
    alert("I've got a name!");
}

Checking If a Key Exists

To see if a property is defined in object, we can use “in” operator to check it.

"key" in object         // true if key exist

Iterating Over Keys-Values

Iterating a keys-values pair is like using foreach, iterating each element of an object. JavaScript has made a special syntax for..in to do so. This syntax will list object properties, using a “pointer” to point to a properties one at a time.

for (key in obj) {
    ... obj[key] ... operated
}

Let’s see how we do it:

var menu = {
    width:  300,
    height: 200,
    title: "Menu"
};

for(var key in menu) {
    var val = menu[key];

    alert("Key: "+key+" value:"+val);
}

There, the key will enumerate the key inside object menu. The key would be “width”, “height”, “title”.

In theory, the order of iteration over object properties is not guaranteed. In practice, there is a de-facto standard about it.

Object Variables are References

A variable which is assigned to object actually keeps reference to it. That is, a variable stores kind-of pointer to real data.

We can use the variable to change this data, this will affect all other references.

var user = { name: 'Xathrya' };   // user is reference to the object
var obj = user;                   // obj ans user refer to same object
obj.name = 'Sabertooth';          // change data in the object

alert(user.name);                 // now it is 'Sabertooth'

A major drawback is JavaScript have characteristic like Java. The variable is reference, not a value / pointer. Therefore we cannot modify the value of object directly.

function increment(val) {
    val++;
}

var val = 5;
increment(val);
alert(val);          // val is still 5

Instead, we can still do this, pass the value inside of a container instead of the reference.

var obj = { val: 5 }
function increment(obj) {
    obj.val++;
}

increment(obj)
alert(obj.val);        // obj.val is now 6

The difference is because in first example variable val is changed, while in second example obj is not changed, but data which it references is modified instead.

Properties and Methods

We can store anything in object. Not just a simple value, but also functions. Remember that functions is also key-value pair with value as function.

var car = {
    name: "XathCar",
    model: 500,
    weight: 850,
    color: "white",

    curSpeed: 0,

    start: function() {
         alert("Car is started");
         this.curSpeed = 0;
    }

    drive: function() {
         alert("Car is running");
         this.curSpeed += 10;
    }

    brake: function() {
         alert("A brake is pressed");
         this.curSpeed -= 5;
    }
};

Here we have functions stored by key ‘start’, ‘drive’, and ‘brake’.

Note the this keyword inside the functions. When a function is called from the object, this become a reference to the object.

To call a method, we can use something like this:

car.start();
car.drive();
car.brake();

To check if a method is exists, we can just check it using if syntax:

if (car.start) car.start();

Constructor

Constructing an object can use new function.

The thing which will be an object should be declared as a function. The function then can have some properties and also some methods. Inside the function, we also have this pointer. Instantiation will take a function name and a keyword new before it.

For example:

function Animal(name) {
    this.name = name;
    this.canWalk = true;
    this.canFly = true;
}

var animal = new Animal("PenQueen");

alert(animal.name);

Which has same result as:

var animal = {
    name: "PenQueen",
    canWalk: true,
    canFly: true
}

If the function returns an object, `this` is ignored.

function Animal() {
    this.name = 'Kitty'
    return { name: 'Salamander' }  // <-- will be returned
}

alert( new Animal().name )         // Salamander

Convention speaking: all functions which are meant to create objects with new have uppercased first letter in the name.

If the function don’t take any arguments, we may omit braces.

Built-In Object

The standard library of JavaScript includes a list of built-in objects. They are, for example:

  • Math – provides methods for mathematical computations,
  • Date – for dates,
  • RegExp – for regular expressions.

Function are also objects, instances of the new Function.

For browser, there are also global object / variable such as:

  • Document
  • Window

,

About Author

about author

xathrya

A man who is obsessed to low level technology.

Leave a Reply

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

Social media & sharing icons powered by UltimatelySocial