Object Basics
JavaScript is an object-oriented language. JavaScript treats everything as an object. Object is an unordered list with a collection of primitive data types, functions and even with other objects. A javaScript object is an entity having key and value. JavaScript is a template-based language, not a class-based language. To obtain the object, we do not create a class. But we direct the creation of objects.
Work out
var person = {
firstName: "John",
lastName: "Rice",
Age: 27,
DOB: "01-01-2000",
};
console.log(person);
// expected output: { firstName: "John", lastName: "Rice", age: 27, DOB: "01-01-2000" }
Creating Objects in JavaScript
There are 3 ways to create objects:
- By using object literal
- By creating an instance of the object by using new keyword
- By using an object constructor
Creating object using object literal
Syntax
The syntax for creating objects using object literal method is
object = { property1: "value1", property2: "value2", property3: "value3"}
Example
var student = {
name: "Sara David",
standard: 10,
school: "ABC School",
};
console.log(student);
// expected output: { name: "Sara David", standard: 10, school: "ABC School" }
Creating object using new keyword
Syntax
The syntax for creating a new object using the new keyword is
var objectName = new Object();
let objectName = new Object();
The new keyword is used to create a new object.
Example
var student = new Object();
student.name = "Sara David";
student.standard = 10;
student.school = "ABC School";
console.log(student);
// expected output: { name: "Sara David", standard: 10, school: "ABC School" }
Creating object using constructor
The this keyword is used to create a new object. A function is created and arguments passed as argument to this function is assigned to the object using this keyword.
Example
function student(name, standard, school) {
this.name = name;
this.standard = standard;
this.school = school;
}
var student1 = new student("Sara David", 10, "ABC School");
console.log(student1);
// expected output: student { name: "Sara David", standard: 10, school: "ABC School" }