In Javascript, Objects are one of the fundamental data types and are used to represent and store collections of key-value pairs.
Objects can store complex data structures. such as attributes, methods etc.
Objects can be created using the object literal syntax {} or with the Object constructor.
The most common way to create an object is using the object literal syntax, where we define key-value pairs inside curly braces `{}`.
const person = { name: "Alice", age: 23, isStudent: true, sayHello: function() { console.log("Hello, my name is " + this.name); } };
"person" is an object with properties like "name", "age", "isStudent", and a method "sayHello".
console.log(person.name); // Outputs: Alice console.log(person['age']); // Outputs: 23 console.log(person.isStudent); // Outputs: true person.sayHello(); // Outputs: Hello, my name is Alice
We can access object properties using dot notation (object.property) or square bracket notation (object['property']):
person.profession = "HR"; person['age'] = 28; console.log(person.job); // Outputs: HR console.log(person.age); // Outputs: 28
delete person.age; console.log(person.age); // Outputs: undefined
We can add new properties or modify existing ones in the object.
const car = { brand: "Land Rover", model: "Defender", start: function() { console.log(this.brand + " " + this.model + " is starting."); }, blowHorn: function() { console.log(" pee pee!"); } }; car.start(); // Output: Land Rover Defender is starting. car.blowHorn() // Output: pee pee!
const person = new Object(); person.name = "Edward Collin"; person.age = 33; console.log(person.title); // Outputs: Edward Collin console.log(person.age); // Outputs: 33
We can delete properties using the `delete` keyword.
Objects can contain functions as properties, which are then referred to as methods.
We can create objects using the "new" keyword and assign values to the attributes.