JavaScript Object is a non-primitive data-type that allows storing multiple unordered collections of data.
Example of an Object:
How to Display JavaScript Objects:
● In the browser console: the console.log() method is used to display an object for debugging purpose.
For example:
const myObj = {
name : 'Satyo',
age : 36
}
console.log(myObj);
Will display:
{name: 'Satyo', age: 36}
● In the browser: getting the output in the browser.
const myObj = {
name : 'Satyo',
age : 36
}
//for output in Dialog Box
alert(myObj);
//for output inside an HTML Element
document.getElementById('demo').innerHTML = myObj;
The output is [object Object]. This happens because the alert() or getElementById() methods display a string format for the object myObj. [object Object] is the string representation of a JS object data type.
Some common solutions to display JavaScript objects in the browser are:
1. Displaying the Object Properties by name: Ex. myObj.age
const myObj = {
name : 'Satyo',
age : 36
}
document.getElementById('demo').innerHTML = myObj.age; // 36
2. Displaying the Object Properties in a loop: Ex. for loop.
const myObj = {
name : 'Satyo',
age : 36
}
let txt = '';
for (let x in myObj) {
txt += myObj[x] + ' ';
};
document.getElementById('demo').innerHTML = txt; // Satyo 36
3. Displaying the Object using:
Object.keys(objectName) - returns an array of keys.
Object.values(objectName) - returns an array of values.
Object.entries(objectName) - returns an array of [key,value] pairs.
const myObj = {
name : 'Satyo',
age : 36
}
document.getElementById('demo').innerHTML = Object.keys(myObj);
// name,age
document.getElementById('demo').innerHTML = Object.values(myObj);
// Satyo,36
document.getElementById('demo').innerHTML = Object.entries(myObj);
// name,Satyo,age,36
4. Displaying the Object using JSON.stringify(objectName) method: this method can change an object into a string and display the entire object as a string or text format.
const myObj = {
name : 'Satyo',
age : 36
}
document.getElementById('demo').innerHTML = JSON.stringify(myObj);
//Now myObj is a text format or string.
It returns:
{"name":"Satyo","age":36}
How to Read, Write, Modify, Delete, and Check Properties of an Object:
● access or read properties of an object using the dot notation . or the array-like/bracket notation [].
Syntax:
for dot notation:
objectName.propertyName;
for bracket notation:
objectName[string expression of propertyName];
Or,
objectName['propertyName'];
Example:
console.log( myObj.name ); // Broto
console.log( myObj['name'] ); // Broto
● add or write new property of an object.
Syntax:
objectName.PropertyName = Value;
Or, objectName['PropertyName'] = Value;
Example:
const myObj = {
…
};
myObj.middleName = 'Dan'; // add new property
myObj['lastName'] = 'Hopper'; // add new property
myObj.year = 2023; // add new property
console.log( myObj );
//{..., lastName: 'Hopper', middleName: 'Dan', year: 2023}
● modify the value of existing property of an object.
Syntax:
objectName.PropertyName = newValue;
Or, objectName['PropertyName'] = newValue;
Example:
const myObj = {
name : 'Broto',
age : 30
};
myObj['name'] = 'Jensen'; //modify 'Jensen' instead of 'Broto'
myObj.age = 40; //modify 40 instead of 30
console.log( myObj ); // {name: Jensen, age : 40}
● Deleting a property from an object:
Syntax:
delete objectName.propertyName; Or delete objectName.propertyName];
Example:
delete myObj['name'];
delete myObj.age;
● Checking if a property exists in an object:
Syntax:
propertyName in objectName
Example:
const myObj = {
name :'Broto',
age : 30,
isStudent : true,
language : ['English', 'Danish', 'Swedish']
};
console.log( 'citizenship' in myObj ); // false
console.log( 'name' in myObj ); // true
Difference between DOT notaion and ARRAY-LIKE notation:
● Accessing properties:
DOT notation( . ): It only accepts static name / key (the key is typed directly).
const myObj = {
name : 'Broto',
language : 'Danish'
}
let myLang = 'language';
console.log(myObj.myLang) // undefined
In the above example, using Dot notation program only looks for the property with the name / key myLang in myObj. Since the property name myLang does not exist in myObj, the result is undefined.
ARRAY-LIKE notation( [] ): It allows dynamic name / key (that means the name/key is evaluated from an expression during runtime). This notation accepts any expression that evaluates to a value. In the example below, in the bracket myLang is a variable. That evaluates to language which is the value Danish in myObj.
const myObj = {name : 'Broto', language : 'Danish' } let myLang = 'language'; console.log(myObj[myLang]) // Danish
Do not use a string expression like:
console.log(myObj['myLang']) //undefined
The 'myLang' serves as the name/key for accessing the property in the object. Since there is no myLang property name in myObj, the result will be undefined.
● Modifying properties:
DOT notation: . notation adds new property in object.
const myObj = {
name : 'Broto',
language : 'Danish'
}
let myLang = 'language';
myObj.myLang = 'English'; // adds new property in object
console.log(myObj)
//{name: 'Broto', language: 'Danish', myLang: 'English'}
ARRAY-LIKE notation: [] notation updates or modifies property in object.
const myObj = {
name : 'Broto',
language : 'Danish'
}
let myLang = 'language';
myObj[myLang] = 'English'; //[] notation updates/modifies property in object
console.log(myObj) //{name: 'Broto', language: 'English'}
How to access Method of an Object in JavaScript:
Syntax:
objectName.methodName();
Example:
const myObj = {
name :'Broto',
getDetails : function () { In short getDetails() {…}
return 'Hello World!';
}
};
console.log( myObj.getDetails() ); // Hello World!
● Pass values in a method using parameters. For Example:
const myObj = {
name :'Broto',
getDetails( a,b ) {
return a + b;
}
};
console.log( myObj.getDetails('Hello from ', 'me') );
// Hello from me
● Access a property of an object from within a method of the same object. For example:
const myObj = {
name :'Broto',
language : ['English', 'Danish'],
address : {
street : 'Green House',
city : 'Copenhagen'
},
getDetails() {
return ('Name: ' + myObj.name + ', Language: ' + myObj.language[1] +
', City: ' + myObj.address.city);
}
};
console.log( myObj.getDetails() );
// Name: Broto, Language: Danish, City: Copenhagen
'this' keyword in JavaScript
In JavaScript, this refers to an object. The this is not a variable; it is a keyword. The this keyword is use to access a property of an object from within a method of the same object.
Using the this keyword in the above example:
const myObj = {
…
…
…
getDetails : function () {
return ('Name: ' + this.name + ', Language: ' +
this.language[1] + ', City: ' + this.address.city);
}
};
console.log( myObj.getDetails() );
//Name: Broto, Language: Danish, City: Copenhagen
In the above example, this.name refers to myObj.name, this.language[1] refers to myObj.language[1], and so on.
How to create a new Object:
There are several ways to create new objects:
● By Object Literal – the most commonly and easiest way to create an object. It is also called object initializer.
Syntax:
const myObj = {}
Example:
const myInfo = {
name : 'Broto',
age : 40
}
console.log(myInfo['name']) // Broto
console.log(myInfo.age) // 40
● By Instance of Object – using new Object().
Example:
const myInfo = new Object();
myInfo.name = 'Broto';
myInfo.age = 40;
console.log(myInfo['name']) // Broto
console.log(myInfo.age) // 40
● By Object Constructor – useful to create multiple objects. First create a constructor function with a capital first letter. Then create an instance of the object with new keyword. That means objects are created by calling the constructor function with the new keyword.
Example:
function Student(stnName, stnAge) { //'Student' constructor function
this.name = stnName, //'name' assigning parameter to the calling object
this.age = stnAge, //'age' assigning parameter to the calling object
this.fullInfo = function () {
return ('Student name is ' + this.name + ' , Age ' + this.age);
}
}
// create objects and assign its properties values.
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
// access objects properties and methods.
console.log(studentInfo1.age); // 40
console.log(studentInfo2.fullInfo()); // Student name is Satyo , Age 35
console.log(studentInfo1.fullInfo()); // Student name is Broto , Age 40
How to add a new Property Or a new Method to a Constructor Function:
To add a new property or method to a constructor, must add it to the constructor function or the JavaScript prototype allows adding new properties or methods to object constructors.
The prototype is an object that is associated with every function by default in the JavaScript .The prototype is special type of enumerable object to which additional properties can be attached to it which will be shared across all the instances of its constructor function.
Syntax:
constructorName.prototype.propertyName = propertyValue;
Without prototype:
function Student(stnName, stnAge) {
this.name = stnName,
this.age = stnAge
}
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
//add property to object studentInfo1
studentInfo1.gender = 'Male';
console.log(studentInfo1.gender); // Male
console.log(studentInfo2.gender); // undefined
In the above example, gender property is attached to studentInfo1 object/instance. However, studentInfo2 object will not have gender property because it is defined only on studentInfo1 object.
With prototype:
function Student(stnName, stnAge) {
this.name = stnName,
this.age = stnAge
}
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
// add property nationality to constructor function using prototype
Student.prototype.nationality = 'Danish';
//add method greet to constructor function using prototype
Student.prototype.greet = function() {
return ('Hello, this is ' + this.name +', age '+ this.age +
', and ' + this.nationality + ' nationality.');
}
console.log(studentInfo2.nationality); // Danish
console.log(studentInfo1.nationality); // Danish
console.log(studentInfo1.greet());
//Hello, this is Broto, age 40, and Danish nationality.
In the above example, both studentInfo1 and studentInfo2 inherits the property nationality from the prototype property of Student construction function.
● Access the prototype property of a constructor function, fx. Student:
Syntax:
constructorName.prototype;
Example:
function Student(stnName, stnAge) {
this.name = stnName,
this.age = stnAge
}
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
console.log(Student.prototype);
//{constructor: Æ’}; It shows an empty object {...} because there is
//no prototype property value at the moment.
//Add a prototype property
Student.prototype.nationality = 'Danish';
console.log(Student.prototype);
//{nationality: 'Danish', constructor: Æ’}
● Access the prototype property of a constructor function from an object, fx. studentInfo1:
Syntax:
Object.getPrototypeOf(objectName);
Example:
function Student(stnName, stnAge) {
this.name = stnName,
this.age = stnAge
}
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
Student.prototype.nationality = 'Danish';
console.log(Object.getPrototypeOf(studentInfo1));
//{nationality: 'Danish', constructor: Æ’}
If an object tries to access the same property that is in the constructor function and the prototype, the object takes the property from the constructor function.
For example:
function Student(stnName, stnAge) {
this.name = stnName,
this.age = stnAge
}
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
//add a property that exits in the construction function
Student.prototype.age = 22;
console.log(studentInfo1.age); // 40
console.log(studentInfo2.age); // 35
How to Change Prototype Values:
Syntax:
constructorName.prototype = {prototypeProperty : prototyprePropertyNewValue};
If you change a prototype value, then all the new objects will have the new value. All the old objects will have the old value.
For example:
function Student(stnName, stnAge) {
this.name = stnName,
this.age = stnAge
}
const studentInfo1 = new Student('Broto', 40);
const studentInfo2 = new Student('Satyo', 35);
Student.prototype.nationality = 'Danish';
console.log(studentInfo1.nationality); // Danish
console.log(studentInfo2.nationality); // Danish
//change the property value of prototype
Student.prototype = { nationality : 'USA' }
//create a new object
const studentInfo3 = new Student('Talukder', 25);
console.log(studentInfo1.nationality); // Danish
console.log(studentInfo2.nationality); // Danish
console.log(studentInfo3.nationality); // USA
0 Comments