Objects.

Objects.

ยท

5 min read

JavaScript supports extending data types. JavaScript objects are a great way to define custom data types.

An object is an instance which contains a set of key value pairs. Unlike primitive data types, objects can represent multiple or complex values and can change over their lifetime. The values can be scalar values or functions or even array of other objects.

The syntactic variations for defining an object is discussed further.

Object Initializers

Like the primitive types, objects have a literal syntax: curly bracesv ({and}). Following is the syntax for defining an object:

var identifier = {
    key1:value, Key2: function ()
{
//functions
},
key3: ["content1"," content2"]
}

The contents of an object are called properties or members and properties consist of a name or key and value. Property names must be strings or symbols, and values can be any type (including any objects).

Like all JavaScript variables, both the object name (which could be a normal variable) and the property name can be case sensitive. You can access the properties of an object with a simple dot-notation.

Following is the syntax for accessing Object properties:

objectName.propertyName

Example of Object Initializers

var person = {
firstname: "Tom",
lastname: "Hanks",
func:function(){return "Hello!!"},
};
//access the object values
console.log(person.firstname)
console.log(person.lastname)
console.log(person.func())

The above Example, defines an object person. The object has three properties. The third property refers to a function.

The following output is displayed on successful execution of the above code.

Tom
Hanks
Hello!!

In ES6, assigning a property value that matches a property name, you can omit the property value.

Example:

var foo = 'bar'
var baz = { foo }
console.log(baz.foo)

The above code snippet defines an object baz. The object has a property of foo. The property value is omitted here as ES6 implicity asigns the value of the variable foo to the object's key foo.

Following is the ES5 equivalent of the above code:

var foo = 'bar'
var baz = { foo: foo }
console.log(baz.foo)

The following output is displayed on successful execution of the above code:

bar

With this shorthand syntax, the JS engine looks in the containing scope for a variable with the same name. If it is found, that variable's value is assigned to the property. If it is not found, a reference error is thrown.

The Object() Constructor

JavaScript provides a special constructor function called Object() to build the object. The new operator is used to create an instance for an object. To create an object, the new operator is followed by the constructor method.

Following is the syntax for defining an object:

var obj_name = new Object();
obj_name.property = value;
OR
obj_name["key"] = value

Following is the syntax for accessing a property:

Object_name.property_key

OR

Object_name["property_key"]

The this Keyword

In JavaScript, the thing called this is the object that "owns" the code.

The value of this, when used in an object, is the object itself.

In a constructor function this does not have a value. It is a substitute for the new object. The value of this will become the new object when a new object is created.

Note that this is not a variable. It is a keyword. You cannot change the value of this.

Adding a Property to an Object

Adding a new property to an existing object is easy:

Example:

myFather.nationality = "English";

The property will be added to myFather. Not to myMother. (Not to any other person objects).

Adding a Method to an Object

Example:

myFather.name = function () {
  return this.firstName + " " + this.lastName;
};

Adding a Property to a Constructor

You cannot add a new property to an object constructor the same way you add a new property to an existing object:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.nationality = "English";
}

Adding a Method to a Constructor

Your constructor function can also define methods:

Example:

function Person(first, last, age, eyecolor) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eyecolor;
  this.name = function() {return this.firstName + " " + this.lastName;};
}

You cannot add a new method to an object constructor the same way you add a new method to an existing object.

Adding methods to an object constructor must be done inside the constructor function:

Example:

function Person(firstName, lastName, age, eyeColor) {
  this.firstName = firstName; 
  this.lastName = lastName;
  this.age = age;
  this.eyeColor = eyeColor;
  this.changeName = function (name) {
    this.lastName = name;
  };
}

The changeName() function assigns the value of name to the person's lastName property.

Built-in JavaScript Constructors

JavaScript has built-in constructors for native objects:

var x1 = new Object();    // A new Object object
var x2 = new String();    // A new String object
var x3 = new Number();    // A new Number object
var x4 = new Boolean();   // A new Boolean object
var x5 = new Array();     // A new Array object
var x6 = new RegExp();    // A new RegExp object
var x7 = new Function();  // A new Function object
var x8 = new Date();      // A new Date object

The Math() object is not in the list. Math is a global object. The new keyword cannot be used on Math.

As you can see above, JavaScript has object versions of the primitive data types String, Number, and Boolean. But there is no reason to create complex objects. Primitive values are much faster.

ALSO:

Use object literals {} instead of new Object().

Use string literals "" instead of new String().

Use number literals 12345 instead of new Number().

Use boolean literals true / false instead of new Boolean().

Use array literals [] instead of new Array().

Use pattern literals /()/ instead of new RegExp().

Use function expressions () {} instead of new Function().

Learn More

Did you find this article valuable?

Support Olabode Olusegun by becoming a sponsor. Any amount is appreciated!