Loading lesson path
Objects are variables that can store both values and functions. Values are stored as key:value pairs called properties.
pairs called methods.
In real life, we can describe subjects as objects (a car, a person, a house)
Formula
Car Methods car.name = Fiat car.model = 500 car.weight = 850kg car.color = white car.start()car.drive() car.brake() car.stop() Different cars have the same properties, but the property values can differ from car to car. Different cars have the same methods, but the methods can be performed at different times.
(Fiat, 500, white) to an object named car:
const car = {
type: "Fiat", model: "500", color: "white"
};type, model, and color are properties "Fiat", "500", and "white" are property values
"literally" describes an object using a concise syntax with zero or more key:value pairs inside curly braces to describe all the object properties
{firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}An object literal is the simplest and most common way to define a JavaScript object. All the examples below, create the same JavaScript object:
// Create an Object const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}; Spaces and line breaks are not important. An object literal can span multiple lines:
// Create an Object const person = {
firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"
};You can also create an empty object, and add the properties later:
// Create an Object const person = {};
// Add Properties person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";
You should declare objects with the const keyword.Create a new JavaScript object using new Object()
// Create an Object const person = new Object({
firstName: "John", lastName: "Doe", age: 50, eyeColor: "blue"
});
There is no need to use new Object().For readability, simplicity and speed, use an object literal instead.
You can access object properties in two ways:
Dot Notation objectName.propertyName person.firstName;
Bracket Notation objectName["propertyName"]
person["firstName"];Objects can also have methods. Object methods are actions that can be performed on objects. Object methods are function definitions stored as property values
const person = {
firstName: "John", lastName : "Doe", age : 50, fullName : function() {
return this.firstName + " " + this.lastName;
}
};