Updated December 20, 2023
Table of Content
- Introduction
- Creating Object in JavaScript
- How to Access Objects in JavaScript?
- Characteristics of Object in JavaScript
- Properties of Object in JavaScript
- Methods of Object in JavaScript
- JavaScript Built-In Methods
Introduction to Object in JavaScript
An object in JavaScript is a variable that contains a different value. It acts as a storage space for a set of values. Objects are one of the most important data types in JavaScript. The object contains properties, types and it’s a separate entity. It is a non-primitive datatype. For example, let’s take a football. A football has a weight, shape, color, design, etc. Here football is an object and weight, the shape is the properties of the object. Similarly, In JScript objects will have properties and those properties will define the characteristics of an object. An object can be anything Strings, Numbers, Boolean, Arrays, Functions, and so on. The properties of an object can be used later in the program after we start using an object.
For example, let us consider we have an object “Student”, where its properties are: first_name, last_name, age, student_id, class, etc.
The javascript object representation for this student object would be represented as follows:
Code:
var student = { first_name : 'Anamika',
last_name : 'Rai',
age : 14,
student_id : 20,
class : 'VIII D'
}
Here note that the properties first_name, last_name, and class contain values of String data type, whereas age and student_id are of the number data type.
Creating Object in JavaScript
We can create object in JavaScript with 4 ways,
- Object literals
- “new” keyword
- ES6 class
- create()
1. Object Literals
It is the simplest option to create object in JScript. We can instantiate objects just like variables.
Example:
var database = {
FirstName : "Brad",
LastName : "Pitt",
DateOfBirth : 1975
};
2. “new” keyword
User Defined Objects with “new” keyword: The “new” keyword will create an instance of an object. Object is created using “new” keyword followed by the constructor.
Example:
var manager = new Object();
var library = new Array ("books", "Novel", "Magazine");
var calendar = new Date ("July 4, 1975");
In the above example, Object(), Array(), Date() are constructor methods and these are built-in JavaScript functions.
3. ES6 Class
ECMAScript 6 is defined for creating a new JScript object call the class syntax. Even though JScript is an OOP’s language, before ECMAScript 6, JavaScript did not use class unlike in Java where class are used all the time.
Example:
class student
{
Constructor (Name, Age, DOB)
{
this.Name = Name;
this.Age = Age;
this.DOB = DOB;
this.getName = function()
{
Return "details:" + this.Name + this.Age + this.DOB;
}
}
}
var database = new student("Brad", 45, 1975);
4. create()
Object.create is a pre-built Object type in JavaScript. When you create new object the object.create() method will use object literal as prototype.
Example:
var student
{
Name: "Brad"
Age: 45
DOB = 1975
getName: function()
{
Return "details:" + this.Name + this.Age + this.DOB;
}
};
var Stu1 = object.create(student);
Stu1.Name = "Angel";
Stu1.Age = 35;
Stu1.DOB = 1985;
How to Access Objects in JavaScript?
Now that the object is created, the next thing one needs to know is how do we access it? Well, javascript provides two ways using which one could access the object:
1. Using an Object Instance
Here the object instance is used to access its properties.
Syntax:
object.property
Example:
Consider we have an object student defined
Code:
var student = { name : "Anamika Rai", age : 14, gender : "female" }
Now to access the object and its properties, let’s print it to console:
Code:
console.log ("Student" + student.name + "is" + student.age + "years old.");
// output: Student Anamika Rai is 14 years old.
2. Using Square Brackets
The object property is placed within square brackets after the object itself.
Syntax:
object['property']
Example:
Accessing the above student object using square brackets
Code:
console.log ("Student" + student['name'] + "is" + student['age '] + "years old.");
// output: Student Anamika Rai is 14 years old.
Characteristics of Object in JavaScript
- Objects are bit complex and as objects can have any combination of reference data types and primitive datatypes.
- A reference datatype involves assigning characters or numbers to a reference value, and the assigned char or number has a pointer to its location.
- The pointer points to the location where the object is saved when passing the object from one function to another.
- An object contains methods and property in it.
Properties of Object in JavaScript
The values associated with object are called properties of the object. It can be deleted, changed, and added.
Syntax for Object:
- Method 1:
ObjectName .property// student.age
- Method 2:
ObjectName["property"] // Student ["age"]
Method 1
Code:
<!DOCTYPE html>
<html>
<body>
<h2>JScript Object Properties</h2>
<p>we can use .property otherwise ["property"].</p>
<p id="demo"></p>
<script>
var student = {
stuname:"steve",
age:40,
}
document.getElementById("demo").innerHTML = student.stuname + " is " + student.age + " year old";
</script>
</body>
</html>
Output:
Method 2
Code:
<html>
<body>
<h2>JavaScript Object Properties</h2>
<p>There are two different ways to access an object property:</p>
<p>You can use .property or ["property"].</p>
<p id="demo"></p>
<script>
var student = {
stuname:"robert",
age: 60,
bookname:"Jscript"
};
document.getElementById("demo").innerHTML = student["stuname"] + " is " + student["age"] + " year old.";
</script>
</body>
</html>
Output:
Methods of Object in JavaScript
In an Object, the method is considered as the behavior of an object. Methods are actions that are used on objects.
Syntax:
methodName()
Code:
<html>
<body>
<p> Method 1 for method in object </p>
<p id="dem"></p>
<script>
var student = {
fName: "Steve",
lName : "Smith",
id : 5474,
fullName : function()
{
return this.fName + " " + this.lName;
}
};
document.getElementById("dem").innerHTML = student.fName();
</script>
</body>
</html>
Output:
JavaScript Built-In Methods
Few mostly used javascript methods are as follows:
- create(): As we have already seen above, this method is used to create javascript objects from a prototype object.
- entries(): This method also takes in a javascript object as a parameter and returns an array containing another array of both key-value pairs. Example: Let’s consider our “student” object once more.
- keys(): The keys() method takes in the javascript object as a parameter and returns an array of its properties.
- values(): Similarly, the values method takes in a javascript object as a parameter and returns an array of its values.
- is(): This method takes in a second object as a parameter and determines if both the objects are equal and return a Boolean value. That is, if both objects are equal, then “true” is returned, else “false”.
1. Object.create()
Object.create() method create new object and will link it to existing object.
Code:
const people = {
printIntroduction: function () {
console.log(`My full name is ${this.Fname}. Am I Alive? ${this.isalive}`);
}
};
const ke = Object.create(people);
ke.Fname = "Robert"; // "Fname" is a property set on "ke", but not on "people"
ke.isalive = true;
ke.printIntroduction();
Output:
2. Object.entries()
The Object.entries() returns object’s array consists of enumerable properties [key, value] pair.
Syntax:
Object.entries(obj)
Code:
const student = { 1: 'Steve', 100: 'Smith', 45: 'Christopher' };
console.log(Object.entries(student));
Output:
3. Object.keys()
TheObject.keys() returns enumerable properties of an array, an array-like object, an array-like object with a random key ordering.
Code:
let employee_detail = {
employee_name: 'Steve',
employee_salary: 144,
employee_age : 23
} ;
console.log(Object.keys(employee_detail).length);
The above program will give you the length of the object using object.keys() method.
Output:
4. Object.values()
The Object.value() will return an array of objects own property values. It will collect only the object values and will return an array.
Code:
// Returning property values of an array
var check = ['x', 'y', 'z'];
console.log(Object.values(check));
Output:
4. Object.is()
The Object.is() method in JavaScript checks if two values are exactly the same, without applying any type coercion, and takes special cases into account, such as positive and negative zero.
Code:
console.log(Object.is(5, 5)); // true
console.log(Object.is('Educba', 'Educba')); // true
console.log(Object.is(true, true)); // true
console.log(Object.is(0, -0)); // false
console.log(Object.is(NaN, NaN)); // true
Output:
Conclusion
In JavaScript, we use objects for declaring the value, property of the data which is a very important aspect of the programming. In JScript, each and everything is an object. Programmers use objects, properties of objects, and methods of objects to declare and use the objects in different concepts.
Recommended Articles
We hope that this EDUCBA information on “Object in JavaScript” was beneficial to you. You can view EDUCBA’s recommended articles for more information.