Javascript object
Created By: chatGPT
JavaScript objects are collections of key-value pairs. They are used to store various data and more complex entities. Each key is a string (or Symbol), and the value can be any valid JavaScript data type, such as strings, numbers, arrays, or even other objects. Here’s an example of creating and manipulating a JavaScript object:
const person = {
name: 'John Doe',
age: 30,
isEmployed: true,
hobbies: ['reading', 'traveling', 'coding'],
greet: function() {
console.log(`Hello, my name is ${this.name}.`);
}
};
// Accessing object properties
console.log(person.name); // John Doe
console.log(person.age); // 30
// Calling an object method
person.greet(); // Hello, my name is John Doe.
You can also add or update properties dynamically. For example, if you want to add a new property
email
, you can do it like this:person.email = 'john.doe@example.com';
console.log(person.email); // john.doe@example.com
To remove a property from an object, you can use the
delete
operator. For instance, if you want to remove the age
property:delete person.age;
console.log(person.age); // undefined
Objects can also be nested. This means that you can have an object as a value for another object. Below is an example of a nested object:
const student = {
name: 'Alice',
age: 25,
courses: {
math: 'A',
science: 'B+',
literature: 'A-'
}
};
// Accessing nested object properties
console.log(student.courses.math); // A
In addition, you can use Object methods to manipulate objects. Some of these methods include
Object.keys()
, Object.values()
, and Object.entries()
which help you retrieve keys, values, and key-value pairs. Here’s an example using these methods:const keys = Object.keys(person);
const values = Object.values(person);
const entries = Object.entries(person);
console.log(keys); // Array of keys
console.log(values); // Array of values
console.log(entries); // Array of [key, value] pairs