Q1. What is an object in JavaScript?
An object in JavaScript is a collection of key-value pairs where each key is called a property and each property can store a value such as a string, number, function, array, or another object.
Objects are used to store and organize related data and behavior together.
Example
Objects are used to store and organize related data and behavior together.
Example
const person = { name: "John", age: 25, city: "New York"};
console.log(person.name);Q2. How can you create an Object in JavaScript?
There are multiple ways to create objects in JavaScript:
Using Object Literal
Using Constructor Function
Using Object Constructor
Using Object Literal
const user = { name: "Mike", age: 30};Using Constructor Function
function User(name, age) { this.name = name; this.age = age;}
const user1 = new User("John", 25);Using Object Constructor
const obj = new Object();obj.name = "Alex";Q3. How do you access object properties?
Object properties can be accessed using:
Dot Notation
Bracket Notation
Dot Notation
console.log(person.name);Bracket Notation
console.log(person["age"]);Q4. How can you add properties to an Object?
Properties can be added using dot notation or bracket notation.
Example
Example
const car = {};
car.brand = "Toyota";car["model"] = "Fortuner";
console.log(car);Q5. Can objects contain functions?
Yes, objects can contain functions. These functions are called methods.
Example
Example
const person = { name: "David", greet: function() { console.log("Hello"); }};
person.greet();