In Javascript, objects are a fundamental data type and are used to represent collections of key-value pairs.
Objects allow us to structure and organize data in a more complex and meaningful way.
The most common way to create an object is using the object literal syntax, where we define key-value pairs inside curly braces `{}`.
let person = { name: "Alice", age: 35, isStudent: false };
We can create objects using the "new" keyword and assign values to the attributes.
let person = new Object(); person.name = "Alice"; person.age = 35; person.isStudent = false; console.log(person) // { name: "Alice", age: 35, isStudent: false };
We can access object properties using dot (`.`) notation or square bracket (`[]`) notation.
console.log(person.name); // "Alice" console.log(person["age"]); // 35 console.log(person["isStudent"]); // false
We can modify object properties using the `.` operator or by specifying the key name in square brackets `["keyName"]`.
person.age = 40; person["isStudent"] = true;
We can add new properties in the object using the `.` operator or by specifying the key name in square brackets `["keyName"]`.
person.city = "London"; person["country"] = "England";
Objects can contain other objects as properties.
let address = { street: "123 Main St, Park Avenue", city: "London", country: "England" }; let person = { name: "Alice", age: 30, address: address };
Properties in an object can also be functions, called methods.
let person = { name: "Alice", age: 30, getName: function() { return this.name; } }; person.getName(); // "Alice"
In the above example, `this` keyword is referring to `person` object here.
We can extract properties from objects and assign them to variables.
let person = { name: "Alice", age: 30, getName: function() { return this.name; } }; let { name, age, getName } = person; console.log(name); // "Alice" console.log(age); // 30 console.log(getName()); // "Alice"
`Object.keys()`, `Object.values()` and `Object.entries()`: Introduced in ES7 (ECMAScript 2017) and these functions allow developers to iterate over keys, values or both.
let person = { name: "Alice", age: 30, getName: function() { return this.name; } }; let keys = Object.keys(person); console.log(keys); // ["name", "age", "getName"]
let person = { name: "Alice", age: 30, getName: function() { return this.name; } }; let values = Object.values(person); console.log(values); // ["Alice", 30, function]
let person = { name: "Alice", age: 30, getName: function() { return this.name; } }; for( let [key, value] of Object.entries(person)) { console.log("key: ", key, "value: ", value); // key: "name" value: "Alice" // on iteration each line will print one by one. // key: "age" value: 30 // key: "getName" value: function }