There are multiple ways to create objects in JavaScript. One way is by using the new Object()
syntax, and another is by using the object literal syntax {}
.
const tinderUser = new Object()
const tinderUser = {}
tinderUser.id = "123abc"
tinderUser.name = "Sammy"
tinderUser.isLoggedIn = false
console.log(tinderUser);
Console Output:
{ id: '123abc', name: 'Sammy', isLoggedIn: false }
Nesting Objects
JavaScript allows you to nest objects within objects, which can be useful for organizing related data.
const regularUser = {
email: "some@gmail.com",
fullname: {
userfullname: {
firstname: "hitesh",
lastname: "choudhary"
}
}
}
console.log(regularUser.fullname.userfullname.firstname);
Console Output:
hitesh
const obj1 = {1: "a", 2: "b"}
const obj2 = {3: "a", 4: "b"}
const obj3 = { obj1, obj2 }
console.log(obj3);
Console Output:
{ obj1: { '1': 'a', '2': 'b' }, obj2: { '3': 'a', '4': 'b' } }
const obj1 = {1: "a", 2: "b"}
const obj2 = {3: "a", 4: "b"}
const obj4 = {5: "a", 6: "b"}
const obj3 = Object.assign({}, obj1, obj2, obj4)
console.log(obj3);
Console Output:
{ '1': 'a', '2': 'b', '3': 'a', '4': 'b', '5': 'a', '6': 'b' }
const obj1 = {1: "a", 2: "b"}
const obj2 = {3: "a", 4: "b"}
const obj4 = {5: "a", 6: "b"}
const obj3 = {...obj1, ...obj2, ...obj4}
console.log(obj3);
Console Output:
{ '1': 'a', '2': 'b', '3': 'a', '4': 'b', '5': 'a', '6': 'b' }
Object.keys()
, Object.values()
, and Object.entries()
.
const tinderUser = { id: '123abc', name: 'Sammy', isLoggedIn: false }
console.log(tinderUser);
console.log(Object.keys(tinderUser));
console.log(Object.values(tinderUser));
console.log(Object.entries(tinderUser));
console.log(tinderUser.hasOwnProperty('isLoggedIn'));
Console Output:
{ id: '123abc', name: 'Sammy', isLoggedIn: false }
[ 'id', 'name', 'isLoggedIn' ]
[ '123abc', 'Sammy', false ]
[ [ 'id', '123abc' ], [ 'name', 'Sammy' ], [ 'isLoggedIn', false ] ]
true
The hasOwnProperty()
method is used to check if a specific property exists in an object.
This method is useful for verifying the existence of properties before attempting to access them.
Destructuring Objects
Destructuring allows you to unpack properties from an object into distinct variables.
const course = {
coursename: "js in hindi",
price: "999",
courseInstructor: "hitesh"
};
const {courseInstructor: instructor} = course;
console.log(instructor);
Console Output:
hitesh
Destructuring provides a clean syntax to extract and assign variables from objects.