JS Objects
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
Real life objects, properties, and methods.
In real life, a car is an object. A car has properties like weight and color, and methods like start and stop.
JavaScript Objects
You have already learned that JavaScript variables are containers for data values. Objects are variables too. But objects can contain many values.
This code assigns a simple value to a variable named car:
let car = "Fiat";
This code assigns many values to a variable named car:
let car = {type:"Fiat", model:"500", color:"white"};
Object Definition
You define (and create) a JavaScript object with an object literal. Spaces and line breaks are not important. An object definition can span multiple lines.
Accessing Object Properties
You can access object properties in two ways:
objectName.propertyName
or
objectName["propertyName"]
Object Methods
Objects can also have methods. Methods are actions that can be performed on objects. Methods are stored in properties as function definitions.