We will cover three aspects of objects in this article.
An object in Javascript is a collection of {name:value}
pairs. Essentially, it is a collection of associations between a name (or key) and a value. The value can be a number, a string, an array, a function, or even another object. If the value is a function then it is known as a method.
Let’s take a look at a simple interview candidate object.
//Object Literal
var candidate = {
title: "Mr.",
firstname: "Tanka",
lastname: "Jahari",
call: function(){
console.log(this.title + " " + this.firstname + " "+
this.lastname + " is requested to come inside");
}
};
This representation of an object, enclosed within curly braces, is called **object-literal syntax. **Object literals follow the following syntax rules:
Let’s see how we can call our candidate object
//Invoke the call property of the candidate
candidate.call()
//Fetch the firstname property of the candidate
console.log(candidate['firstname'])
The above syntax only creates a single object. In the real world, however, we often need a blueprint for creating multiple objects. That blueprint is similar to how a class constructor behaves in languages like Python, C++ and Java.
In a strikingly similar fashion JavaScript allows us to create objects by using a constructor function. Objects are created by calling the constructor function with the new
keyword. It is called a **function constructor **because it actually creates a new Function
object.
#javascript #programming #technology #web-development #coding