Skip to content

JavaScript Objects

Reading Mode

JavaScript is an awesome language but at the same time JavaScript is a frustrating language.

Every developer will have this love hate relationship with JavaScript. Developers just don't know how to define JavaScript : Is it Object Oriented? is it a Functional language? Is it an interpreted language , is it a dynamic language?

The truth is, JavaScript comprises of elements of all, and unfortunately not always the in a good way.

At the core of JavaScript is the object.

Everything is an object and the object is everything!

Nearly everything in JavaScript is an object, including Javascript functions, because of that feature, functions can be used anywhere you might use a variable, including the parameters in function calls.

In JavaScript an object is just a container for a collection of named values, otherwise known as properties.

JavaScript has one Complex object, which for the lack of imagination is just called object. JavaScript also has five Simple data types: Number, String, Boolean, Undefined, and Null.

mutable & immutable

/* Freelancer is a constructor function It was written with the intent of being used with the new keyword. */
var Freelancer = function (name, location, rate, available){
    // "this" below is the new object that is being created
    this.name = name;
    this.location = location;
    this.rate = rate;
    this.available = available;
    this.getAvailability = function () { return this.available; };
    };

var gary = new Freelancer('Gary Woodfine', 'United Kingdom', 1000, true);

console.log(gary);

console.log(gary.getAvailability());

An important thing to note here is that in JavaScript an object is mutable and the simple data types are immutable.

Reference Data Type and Primitive Data Types

In JavaScript both Reference Data Types and Primitive data types are compared by value.

There are some interesting edge cases and potential side effects of this functionality you need to be aware of, as the name implies reference data types values are stored as a reference, where as primitive data types are stored as values.

// The primitive data type String is stored as a value
var person = "Gary";
var anotherPerson = person; // anotherPerson = the value of person
person = "John"; // value of person changed

console.log(anotherPerson); // Should Print Gary
console.log(person); // Should Print John

//In the next example we'll create an object and change it's value

var person = {name: "Gary"};
var anotherPerson = person;
person.name = "John";
console.log(anotherPerson.name); // Should Print John
console.log(person.name); // Should Print John

NB : objects are really just containers for properties, each of which has a name and a value. This notion of a container of properties with named values (i.e. an object) is used by JavaScript as the building blocks for expressing values in JavaScript.

Object data properties & attributes

Objects typically store values in an unordered name-value pair collection of properties. Property names are strings, so JavaScript objects map strings to values, however objects also have 3 additional attributes.

  • Configurable : Specifies whether the property can be deleted or changed.
  • Enumerable : Specifies whether the property can be returned in a for/in loop.
  • Writable : Specifies whether the property can be changed.

Even JavaScript types like the String, Number, Date, Boolean are objects. These objects also have constructor functions baked into the language to make the creation of these objects a trivial task.

var myStringObject = new String('Gary Woodfine');
var myObjectObject = new Object();
var myDateObject = new Date();
var myBooleanObject = new Boolean();


myObjectObject ['Name']= 'Gary Woodfine';


console.log(myObjectObject);
console.log(myStringObject);
console.log(myDateObject);
console.log(myBooleanObject);

As it turns out all of the above are objects as they can have properties, inherit properties, and are produced from a constructor function.  It is also possible to create your own powerful object constructor functions .

Object Constructor

You may need to create non-native custom object constructor functions to help other developers to create objects from it. In my case below I want to create a Freelancer object so that I can create a number of freelancer objects from it with all the same traits.

/* Freelancer is a constructor function It was written with the intent of being used with the new keyword. */
var Freelancer = function (name, location, rate, available){
    // "this" below is the new object that is being created
    this.name = name;
    this.location = location;
    this.rate = rate;
    this.available = available;
    this.getAvailability = function () { return this.available; };
    };

var gary = new Freelancer('Gary Woodfine', 'United Kingdom', 1000, true);

console.log(gary);

console.log(gary.getAvailability());

Prototype

In addition to having maintaining their own set of properties JavaScript objects also inherit the properties of another object known as its prototype

Every JavaScript object has a second object associated with it, known as its prototype, and the first object inherits properties from the prototype.

The methods of an object are typically inherited properties and this is called prototypal inheritance.

JavaScript objects are dynamic, meaning properties can be added and deleted.

Creating objects

The most common things to do with objects are to create them and to set, query, delete, test and enumerate their properties.

A property name may be any string, including an empty string, but no object may have two properties with the same name. The value may be any JavaScript value, or it may be a getter or a setter function or both.

The easiest way to create an object is to include an object literal in your JavaScript code. An object literal is a comma-separated list of colon-separated name:value pairs enclosed in curly braces.

var myemptyobject = {};        // An empty object

var mynameobject = {"FirstName" : "Gary", "Lastname" : "Woodfine"};   // object with 2 properties


// A complex object containing a another object
var myblogobject = {
    "title" : "Javascript Object" ,
    "Content" : "Blah Blah ",
    author :{
        "FirstName" : "Gary",
        "Lastname" : "Woodfine"
    }
}

Creating Objects with new keyword

The new keyword creates and initializes a new object and must be followed by a function invocation.  A function used in this way is called a constructor and serves to initialize a newly created object.   Core JavaScript includes built-in constructors for native types.

// Core  constructor objects
var object = new Object();              // Create an empty object i.e. {}
var date = new Date();                  // Create a Date Object
var array = new Array();                // Create an empty array i.e. []
var regex = new RegExp("js");           // Create a Regular Expression object

Objects created using the new keyword and constructor invocation use the value of the prototype property of the constructor functions as their prototype.

Object.create()

In the specification of ECMAScript 5,  an object.create() method is defined, which is a static function invoked on individual objects.

//Create an object with some properties
var personObject = { Name : "", LastName : "", Hair : "", Eyes : "", Job : ""};

//Create a new object inherit properties from the base object
var gary = Object.create(personObject );
    gary.Name = "Gary";
    gary.LastName = "Woodfine";
    gary.Job = "Freelance Software Developer";
    gary.Eyes = "Blue";
    gary.Hair = "Brown";



for(var prop in gary){
    if(gary.hasOwnProperty(prop)) {
        console.log(prop + " = " + gary[prop]);
    }
}

The role of a constructor function is to create multiple objects that share certain qualities and behaviors. Basically, a constructor function is a cookie cutter for producing objects that have default properties and property methods.

In JavaScript, most values  involve objects being created, or instantiated, from a constructor function.  An object returned from a constructor is called an instance. Make sure you are comfortable with these semantics, as well as the pattern of leveraging constructors to produce objects.

 Native JavaScript object constructors

The JavaScript language contains nine native or built-in object constructors.  These objects are used by JavaScript to used to express object values in JavaScript code, as well as orchestrate several features of the language. The native object constructors are multifaceted in that they produce objects, but are also leveraged in facilitating many of the language’s programming conventions. For example, functions are objects created from the Function() constructor, but are also used to create other objects when called as constructor functions using the new keyword.

The nine native object constructors that come prepackaged with JavaScript are:

  • number
  • String
  • Boolean
  • Object
  • Array
  • function
  • Date
  • RegExp
  • Error
Gary Woodfine
Latest posts by Gary Woodfine (see all)