Objects in Javascript
Object is a non-primitive data type in JavaScript. It is like any other variable, the only difference is that an object holds multiple values in terms of properties and methods. Properties can hold values of primitive data types and methods are functions.
In other programming languages like Java or C#, you need a class to create an object of it. In JavaScript, an object is a standalone entity because there is no class in JavaScript. However, you can achieve class like functionality using functions. We will learn how to treat a function as a class in the advance JavaScript section.
Let's learn how to create an object in JavaScript.
In JavaScript, an object can be created in two ways:
- Object literal
- Object constructor
Object Literal
The object literal is a simple way of creating an object using { } brackets. You can include key-value pair in { }, where key would be property or method name and value will be value of property of any data type or a function. Use comma (,) to separate multiple key-value pairs.
Syntax:
var <object-name> = { key1: value1, key2: value2,... keyN: valueN};
The following example creates an object using object literal syntax.
Example: Create Object using Object Literal Syntax
var emptyObject = {}; // object with no properties or methods
var person = { firstName: "John" }; // object with single property
// object with single method
var message = {
showMessage: function (val) {
alert(val);
}
};
// object with properties & method
var person = {
firstName: "James",
lastName: "Bond",
age: 15,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
Access JavaScript Object Properties & Methods
var person = {
firstName: "James",
lastName: "Bond",
age: 25,
getFullName: function () {
return this.firstName + ' ' + this.lastName
}
};
person.firstName; // returns James
person.lastName; // returns Bond
person["firstName"];// returns James
person["lastName"];// returns Bond
person.getFullName();
Adding or Removing Properties in Javascript | Javascript Object Oriented Programming
Understanding Objects