JavaScript Objects

About JavaScript Object

JavaScript object is a collection of properties.

Object allows programmers to store data in key-value pairs in a structured manner.

Each key of object property is a unique identifier.

Value of key can be any data type, including numbers, strings, arrays, functions, or even other objects.

Objects are reference types.

Understanding objects is crucial for working with JavaScript, as they are used extensively in web development.

Creating JavaScript Object

JavaScript objects can be created primary in three ways- object literal syntax, object constructor, and object constructor function.

Object Literal Syntax:

An object can be defined using curly braces '{}'. The key-value pairs are placed within the curly braces '{}' as demonstrated in the following example:

Example of Creating Object Using Object Literal Syntax
Explanation of the code
  • const student: This line declares a constant variable named ‘student’.
  • {firstName: "John", lastName: "Smith", program: "CSE" age: 22 }; : This line defines an object and the object is assigned to the variable 'student'.
  • firstName: "John", lastName: "Smith", program: "CSE" age: 22: In the object, firstName: "John", lastName: "Smith", program: "CSE" and age: 22 are the properties of the object. They are key-value paired. As for the first property firstName: "John", firstName is the name of the object property (key) and "John" is the value of the property. Colon (:) is used to pair value with the key.
  • console.log(student);: This line of code prints the 'student' object in the console.

Object Constructor:

An object can be created by using the Object constructor 'new Object()' as demonstrated in the following example:

Example of Creating Object Using Object Constructor
Explanation of the code
  • const student = new Object();: This line creates an empty object named ‘student’ using object constructor 'new Object()'.
  • student.firstName = "John" ... student.age = 22; : Properties are added to the 'student' object.
  • console.log(student);: This line of code prints the object in the console.

Object Constructor Function (Advanced level):

An object can be created by using the Object constructor function as demonstrated in the following example:

Example of Creating Object Using Object Constructor Function
Explanation of the code
  • function Student(firstName, lastName, program, age){...};: The Student constructor function initializes new object with the properties: 'firstName', 'lastName', 'program' and 'age'.
  • const studentObj1 = new Student("John", "Smith", "CSE", 25);: This line calls Student constructor function by passing the arguments ("John", "Smith", "CSE", 25). Thus a new object named 'studentObj1' is created.
  • const studentObj2 = new Student("Bob", "Johnson", "EEE", 32);: This line calls Student constructor function by passing the arguments ("Bob", "Johnson", "EEE", 32). Thus another new object named 'studentObj2' is created.
  • console.log(studentObj1);: This line of code prints the student object 'studentObj1' in the console.
  • console.log(studentObj2);: This line of code prints the student object 'studentObj2' in the console.

Accessing Object Properties

Object properties can be accessed in two ways:

Dot Notation:

An object property can be accessed using a dot(.) after object name followed by property name (e.g. student.firstName) as demonstrated in the following example:

Example of Accessing Object Properties Using Dot
Output of the above example
John
                            
Explanation of the code
  • console.log(student.firstName);: The code 'student.firstName' accesses the 'firstName' property of the 'student' object and returns the value of the property.

Bracket Notation:

An object property can be accessed using square bracket [] after object name and property name is placed within the square bracket [] (e.g. student["firstName"]) as demonstrated in the following example:

Example of Accessing Object Properties Using Square Brackets
Output of the above example
John
                            
Explanation of the code
  • console.log(student["firstName"]);: The code 'student["firstName"])' accesses the 'firstName' property of the 'student' object and returns the value of the property. Please note that the property name must be placed inside single or double quotes.

Manipulating Object & Its Properties

Adding Properties to Object:

Just add new object property name with a dot (.) after the object name and assign a value (e.g. objectName.newPropertyName = vaule).

Example of Adding Properties to Object
Output of the above example
{ firstName: "John", lastName: "Smith", GPA: 4 }
                            
Explanation of the code
  • student.GPA = 4.0;: This line of code adds a property name 'GPA' to the 'student' object and assigns the value 4.0 to the property.

Removing Object Properties:

Object properties can be removed from an object using the delete operator:

Example of Removing Object Properties
Output of the above example
{ firstName: "John", lastName: "Smith" }
                            
Explanation of the code
  • delete student.GPA;: In the line of code, the delete operator is used to remove 'GPA' property from the 'student' object.

Updating Object Property Value

Object's property value can be updated by just assigning new value to the object property that needs to be updated (e.g. objectName.propertyName = newVaule):

Example of Updating Object's Property Value
Output of the above example
{ firstName: "John", lastName: "Smith", program: "EEE" }
                            
Explanation of the code
  • student.program = "EEE";: This line of code updates the value of program property of the 'student' object "CSE" to "EEE".

Checking Object Property

The in operator or hasOwnProperty() method is used to check if an object has a property.

Example of Checking Object Property

Iterating Over Object Properties

The for...in loop iterates over the object's enumerable property keys as demonstrated in the following example:

Example of Iterating Over Object Properties
Output of the above example
firstName: John
lastName: Smith
program: CSE
                            
Explanation of the Code:
  • for (let key in student): This line of code defines for..in loop using for keyword which iterates over the keys (firstName, lastName, program ) of student object.
  • console.log(`${key}: ${ student[key]}`); : This line prints the keys and values of the object in the console.

Methods of Object Class (Advanced Level)

1. Object.create():

Object.create() method creates a new object with the specified prototype and optional properties.

Example of Object.create()

2. Object.keys():

Object.keys() method returns an array of the object’s property names i.e. keys.

Example of Object.keys()

3. Object.values():

Object.values() method returns an array of the object’s property values.

Example of Object.values()

4. Object.entries():

Object.entries() method returns an array of the object’s key-value pairs as nested arrays.

Example of Object.entries()

5. Object.assign():

Object.assign() method copies the values of all enumerable properties from one or more source objects to a target object.

Example of Object.assign()

6. Object.freeze():

Object.freeze() method freezes the object, making it immutable (you can't add, delete, or modify properties).

Example of Object.freeze()

7. Object.seal():

Object.seal() method seals the object, preventing the addition or removal of properties, but allows modification of existing ones.

Example of Object.seal()

8. Object.getOwnPropertyDescriptor():

Object.getOwnPropertyDescriptor() method returns the descriptor object for a specified property of an object.

Example of Object.getOwnPropertyDescriptor()

9. Object.getOwnPropertyDescriptors():

Object.getOwnPropertyDescriptors() method returns all property descriptors of an object.

Example of Object.getOwnPropertyDescriptors()

10. Object.getPrototypeOf():

Object.getPrototypeOf() method gets the prototype of the specified object.

Example of Object.getPrototypeOf()

11. Object.setPrototypeOf():

Object.setPrototypeOf() method sets the prototype of an object.

Example of Object.setPrototypeOf()

12. Object.defineProperty():

Object.defineProperty() method defines a new property or modifies an existing property of an object.

Example of Object.defineProperty()

13. Object.defineProperties():

Object.defineProperties() method defines multiple properties at once.

Example of Object.defineProperty()

14. Object.is():

Object.is() method compares two values to determine if they are the same value and returns Boolean value.

Example of Object.is()

15. Object.isFrozen():

Object.isFrozen() method checks if an object is frozen and returns Boolean value.

Example of Object.isFrozen()

16. Object.isSealed():

Object.isSealed() method checks if an object is sealed and returns Boolean value.

Example of Object.isSealed()

17. Object.preventExtensions():

Object.preventExtensions() method prevents from adding new properties to the object.

Example of Object.preventExtensions()

18. Object.isExtensible():

Object.isExtensible() method checks whether new property can be added to the object.

Example of Object.isExtensible()

19. Object.fromEntries():

Object.fromEntries() method creates an object from an array of key-value pairs and returns the object.

Example of Object.fromEntries()

JavaScript Compiler For Live Practice

Practice the above JavaScript code in the following JavaScript Editor. Create more JavaScript objects and experiment with object properties and methods in the following editor and click Execute button to check the output. The output will be displayed in JavaScript Code Output section.

JavaScript logo JavaScript Editor
JavaScript Code Output