Objects in JavaScript


In this JavaScript tutorial, we are going to learn "Objects in JavaScript", and much more about objects.

What are objects in JavaScript?

  • An object is used to store multiple collections of data.

  • It is a non-primitive data type in JavaScript.

  • Each member of an object is a key: value pair.

  • In JavaScript, object can represent real-world entities or abstract concepts.

  • JavaScript is an object-based language, So everything is an object in JavaScript.


JavaScript object Declaration Syntax

let myObject = {
    key1: value1,
    key2: value2,
    key3: value3
}

console.log(myObject[2]);


Access Object in JavaScript

let obj = {
    name: "Raju",
    page: "raju_webdev",
    role: "web developer"
}

//Accessing Object
for (let key in obj) {
    console.log(`${key} : ${obj[key]}`);
}

//Accessing name key in object
console.log(obj.name);

//Accessing page in object
console.log(obj['page']);


Access Object Property in JavaScript

// Create an object

var person = {
    firstName: 'Raju',
    lastName: 'Sheoran',
    age: 20,
    address: {
        street: '1635 XYZ',
        city: 'Hisar',
        state: 'HR'
    }
}

// Access object properties using dot notation
console.log(person.firstName);// Output: Raju
console.log(person.lastName); // Output: Sheoran

// Access nested object properties
console.log(person.address.street); // Output: 1635 XYZ
console.log(person.address.city); // Output: Hisar
console.log(person.address.state); // Output: HR


// Access object properties using bracket notation
console.log(person['firstName']); // Output: Raju
console.log(person['lastName']); // Output: Sheoran

// Access nested object properties using bracket notation
console.log(person['address']['street']); // Output: 1635 XYZ
console.log(person['address']['city']); // Output: Hisar
console.log(person['address']['state']); // Output: HR

In this code, we have an object person with properties such as firstName, lastName, age, and address. We can access these properties using dot notation (object.property) or bracket notation (object['property']).

When accessing nested properties, we can chain the dot notation or use multiple brackets to access the desired property.

Javascript Object Methods With Example

1. Object.assign()

This JavaScript Object method is used to copy enumerable and own properties from a source object to a target object.

// Create a targetObj object
const targetObj = { name: 'Raju' };

// Create a sourceObj object
const sourceObj = { age: 20, city: 'Hisar' };

// Assign properties from the sourceObj object to the targetObj object
const result = Object.assign(targetObj, sourceObj);

// Output the result
console.log(result);
// Output: { name: 'Raju', age: 20, city: 'Hisar' }


2. Object.create()

This JavaScript Object method is used to create a new object with the specified prototype object and properties.

// Create a prototype object
const personPrototype = {
    greet: function () {
        console.log(`Hello, my name is ${this.name}.`);
    }
};

// Create a new object using the prototype
const raju = Object.create(personPrototype);
raju.name = 'Raju';

// Call the method defined in the prototype
raju.greet();
// Output: Hello, my name is Raju.


3. Object.defineProperty()

This JavaScript Object method is used to describe some behavioral attributes of the property.

// Create an object
const person = {};

// Define a property using Object.defineProperty()
Object.defineProperty(person, 'name', {
    value: 'Raju',
    writable: false,
    enumerable: true,
    configurable: true
});

// Access the property
console.log(person.name);
// Output: Raju

// Attempt to modify the property
person.name = 'Raj';

// Access the property again
console.log(person.name);
// Output: Raju


4. Object.defineProperties()

This JavaScript Object method is used to create and configure multiple object properties.

// Create an empty object
const person = {};

// Define multiple properties using Object.defineProperties()
Object.defineProperties(person, {
    name: {
        value: 'Raju',
        writable: false
    },
    age: {
        value: 20,
        writable: true
    },
    city: {
        value: 'Hisar',
        writable: true
    }
});

// Access the properties
console.log(person.name);
// Output: Raju

console.log(person.age);
// Output: 20

console.log(person.city);
// Output: Hisar

// Attempt to modify the properties
person.name = 'Jassi'; // Ignored due to writable: false
person.age = 20;
person.city = 'Rohtak';

// Access the properties again
console.log(person.name);
// Output: Raju

5. Object.entries()

This JavaScript Object method returns an array with arrays of the key, and value pairs.

// Create an object
const person = { Name: 'Raju', Age: 20, City: 'Hisar' };

// Get an array of key-value pairs using Object.entries()
const entries = Object.entries(person);

// Output the key-value pairs
for (const [key, value] of entries) {
    console.log(`${key}: ${value}`);
}

// Output:
Name: Raju
Age: 20
City: Hisar


6. Object.freeze()

This JavaScript Object method is used to prevent existing properties from being removed.

// Create an object
const person = { name: 'Raju', age: 20 };

// Freeze the object using Object.freeze()
Object.freeze(person);

// Attempt to modify the properties
person.name = 'Jassi';
person.age = 21;

// Output the modified properties
console.log(person.name);
console.log(person.age);

// Output:
Raju
20


7. Object.getOwnPropertyDescriptor()

This JavaScript Object method returns a property descriptor for the specified property of the specified object.

// Create an object
const person = {
    Name: 'Raju',
    age: 20
};

// Get the property descriptor of the 'Name' property
const nameDescriptor = Object.getOwnPropertyDescriptor(person, 'Name');

// Output the property descriptor
console.log(nameDescriptor);

// Output:
{ value: 'Raju', writable: true, enumerable: true, configurable: true }


8. Object.getOwnPropertyDescriptors()

This JavaScript Object method returns all own property descriptors of a given object.

const person = {
    firstName: 'Raju',
    lastName: 'Doe',
    get fullName() {
        return `${this.firstName} ${this.lastName}`;
    },
};

const descriptors = Object.getOwnPropertyDescriptors(person);

for (let key in descriptors) {
    console.log(`${key}: `, descriptors[key]);
}

// Output:
firstName:  { value: 'Raju', writable: true, enumerable: true, configurable: true }
lastName:  { value: 'Doe', writable: true, enumerable: true, configurable: true }
fullName:  {
get: [Function: get fullName],
set: undefined,
enumerable: true,
configurable: true
}

9. Object.getOwnPropertyNames()

This JavaScript Object method returns an array of all properties (enumerable or not) found.

const personObj = {
    Name: 'Raju',
    Age: 21,
    Gender: 'Male'
};

const propertyNames = Object.getOwnPropertyNames(personObj);

console.log(propertyNames);

// Output:
[ 'Name', 'Age', 'Gender' ]


10. Object.getOwnPropertySymbols()

This JavaScript Object method returns an array of all own symbol key properties.

const myObj = {};
const sym1 = Symbol('Symbol 1');
const sym2 = Symbol('Symbol 2');
myObj[sym1] = 'value 1';
myObj[sym2] = 'value 2';

const symbols = Object.getOwnPropertySymbols(myObj);

console.log(symbols);

// Output:
[ Symbol(Symbol 1), Symbol(Symbol 2) ]


11. Object.getPrototypeOf()

This method returns the prototype of the specified object.

// Creating a parent object
const parent = {
    greet: function () {
        console.log('Hello, this is parent object!');
    }
};

// Creating a child object
const child = Object.create(parent);

// Print the prototype of the child object
const prototype = Object.getPrototypeOf(child);
console.log(prototype);

// Calling the greet function from the parent object using the child object
child.greet();

// Output:
{ greet: [Function: greet] }
Hello, this is parent object!


12. Object.is()

The Object.is() JavaScript method determines whether two values are the same value. If two values are same then it returns true otherwise it will return false.

let value1 = 5;
let value2 = 5;

console.log(Object.is(value1, value2));
// Output: true

let value3 = 0;
let value4 = -0;

console.log(Object.is(value3, value4));
// Output: false

13. Object.isExtensible()

This JavaScript Object method determines if an object is extensible or not. If it is then it returns true else it will return false.

const obj = { a: 1, b: 2 };
console.log(Object.isExtensible(obj));
// Output: true

Object.preventExtensions(obj);
console.log(Object.isExtensible(obj));
// Output: false


14. Object.isFrozen()

This JavaScript Object method determines if an object was frozen.

const myObj = {
    prop1: 'value1',
    prop2: 'value2'
};

console.log(Object.isFrozen(myObj));

// Freeze the object
Object.freeze(myObj);

console.log(Object.isFrozen(myObj));

// Adding a new property to the frozen object
myObj.prop3 = 'value3';

console.log(myObj.prop3);

// Modifying an existing property of the frozen object
myObj.prop1 = 'new value';

console.log(myObj.prop1);

// Deleting a property from the frozen object
delete myObj.prop2;

console.log(myObj.prop2);


// Output:
false
true
undefined
value1
value2


15. Object.isSealed()

This method determines if an object is sealed.

const myObj = {
    prop1: 'value1',
    prop2: 'value2'
};

console.log(Object.isSealed(myObj));
// Output: false

Object.seal(myObj);

console.log(Object.isSealed(myObj));
// Output:true


16. Object.keys()

This JavaScript Object method returns an array of a given object's property names.

const myObject = {
    name: 'Raju',
    age: 20,
    profession: 'Frontend Developer'
};

const propertyNames = Object.keys(myObject);

console.log(propertyNames);

//Output: [ 'name', 'age', 'profession' ]


17. Object.preventExtensions()

This method is used to prevent any extensions of an object.

const myObject = {
    name: 'Raju',
    age: 20
};

console.log(Object.isExtensible(myObject));
Object.preventExtensions(myObject);
console.log(Object.isExtensible(myObject));

// Trying to add a new property
myObject.email = 'contact.geekshelp@gmail.com';

console.log(myObject.email);
// Output:
true
false
undefined


18. Object.seal()

This method prevents new properties from being added and marks all existing properties as non-configurable.

let person = {
    name: 'Raju',
    age: 20
};

// Sealing the object
Object.seal(person);

// Trying to modify the existing property
person.name = 'Jassi';

// Trying to add a new property
person.gender = 'Male';

console.log(person.name);
console.log(person.gender);

// Output:
Jassi
undefined

19. Object.setPrototypeOf()

This JavaScript Object method sets the prototype of a specified object to another object.

// Create a parent object
const parent = {
    greet() {
        console.log("Hello, this is parent object!");
    },
};

// Create a child object
const child = {
    Name: "Raju",
};

// Set the prototype of the child object to be the parent object
Object.setPrototypeOf(child, parent);

// Now the child object inherits the greet method from the parent object
child.greet();

// Output: Hello, this is parent object!


20. Object.values()

This method returns an array of values of an object.

const person = {
    name: 'Raju',
    age: 20,
    profession: 'Frontend Developer'
};

const values = Object.values(person);

console.log(values);

// Output: [ 'Raju', 20, 'Frontend Developer' ]


21. Object.hasOwnProperty()

Returns a boolean indicating whether an object has a specific property as its own property (not inherited).

const person = {
    name: 'Raju',
    age: 20,
};

console.log(person.hasOwnProperty('name'));
console.log(person.hasOwnProperty('gender'));
// Output:
true
false


22. Object.toString()

This JavaScript Object method returns a string representation of an object.

const person = {
    name: "Raju",
    age: 20,
    occupation: "Developer",
    toString() {
        return `${this.name}, ${this.age} years old, occupation: ${this.occupation}`;
    }
};

console.log(person.toString());

// Output: Raju, 20 years old, occupation: Developer


23. Object.valueOf()

This JavaScript Object method returns the primitive value of an object.

let obj = {
    name: "Raju",
    age: 20,
};

let value = Object.valueOf(obj);

console.log(value);

// Output: [Function: Object]

How to Create Object in JavaScript Dynamically

// Empty object
let obj1 = {};

// Object with properties
let obj2 = { firstName: 'Raju', lastName: 'Sheoran', age: 20 };

// Add properties dynamically
==> obj1.propertyName = propertyValue;
obj1.name = "Raju Webdev";
obj2['website'] = 'Geeks Help';

// Access dynamically added properties
console.log(obj1.name);
console.log(obj2['website']);

In this approach, you can create an empty object (obj1) or an object with predefined properties (obj2).

To add properties dynamically, you can simply assign a value to a new property using dot notation (object.propertyName = propertyValue) or bracket notation (object['newProperty'] = newValue).

The properties can be accessed in a similar manner.


Create JavaScript Object with New Keyword

The following example creates a new JavaScript object using new Object(), and then adds 4 properties:

const person = new Object();
person.firstName = "Raju";
person.lastName = "Sheoran";
person.age = 20;
person.eyeColor = "blue";

console.log(person);

// Output:
{ firstName: 'Raju', lastName: 'Sheoran', age: 20, eyeColor: 'blue' }


JavaScript Create an Object with Array Property

// Object literal with an array property
let person = {
    firstName: 'Raju',
    lastName: 'Sheoran',
    hobbies: ['reading', 'coding', 'PUBG']
};

// Access array property
console.log(person.hobbies);

// Output: [ 'reading', 'coding', 'PUBG' ]


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad