Object in JavaScript
An object is a collection of properties (variables, other objects, & functions), and property is a combination of name (as key) and value. A property’s value can be a function, in this case, the particular property is called as a method. Above capabilities has made JS an OO paradigm.
Like other OO programming language, it can be explained by the real-life tangible objects in JavaScript.
Objects are variables:
JavaScript’s variables can contain single values, you can create your own variable and assign a value in it, which will work as an object.
var person = "John Doe";
However, objects can contain multiple variables. The variables are written as name: value pair.
var person = {
firstName:"John",
lastName:"Doe",
age:50
};
A JavaScript object is a collection of name and value pairs.
Object name and value pair is similar to –
- Associative arrays in PHP
- Dictionaries in Python
- Hash tables in C
Object Methods:
An object method is properity which contains a function definition as a value.
var person = {
firstName:"John",
lastName:"Doe",
age:50,fullName : function(){
return this.firstName + this.lastName
}
};
Accessing properties:
There are two ways to access the properties
- Using dot notation
2. Using bracket notation
Using dot notation
You access the properties of an object with a simple dot-notation.
Syntex : objectName.propertyName
var person = {
firstName:"John",
lastName:"Doe",
age:50,fullName : function(){
return this.firstName + this.lastName
}
};
person.firstName // John
To assign a value to a property
person.firstName = "Kery";
Using []notation
You access the properties of an object with a simple dot-notation.
Syntex : objectName['propertyName']
var person = {
firstName:"John",
lastName:"Doe",
age:50,fullName : function(){
return this.firstName + this.lastName
}
};person['firstName'] // John
person['firstName'] = "Kery";