- OBJECTS
An object is simply a collection of properties, and a property is an association between a name( or key) and a value. An object is a standalone entity, with properties and type.
For example:
let fasterShip = {color : 'silver',
'Fuel Type': 'Turbo Fuel'
};
The name:value pairs in JavaScript objects are called properties. In the above example, color is a property of fasterShip and silver is the property value. The same case with Fuel Type and Turbo Fuel.
Accessing Object Properties
To access the properties in the object, you can either use the dot notation or square brackets.
For Example,
let spaceship = {'Fuel Type' : 'Turbo Fuel',
'Active Mission' : true,
homePlanet : 'Earth',
numCrew: 5
};
Now, to access the numCrew property, you can use either of the 2 ways:Type 1- spaceship.numCrew
Type 2- spaceship["numCrew"]
Methods are actions that can be performed on objects. It is a function stored as a property in an object.
For example:
let alienShip = {
retreat() {
console.log(retreatMessage) },
takeOff() { console.log('Spim... Borp... Glix... Blastoff!') } }
Here, retreat and takeOff are methods(or function definitions) inside the object alienShip.
You can acces the object method with the following syntax: objectName.methodName. If you access a method without (), it will return the function definition.
For Example:
let spaceship = {
telescope: {
yearBuilt: 2018,
model: "91031-XLT",
focalLength: 2032
},
crew: {
captain: {
name: 'Sandra',
degree: 'Computer Engineering',
encourageTeam() { console.log('We got this!') },
'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
},
engine: {
model: "Nimbus2000"
} };
Here, the parent object is spaceship which contains nested objects, being: telescope, crew, and engine.
Properties of an object can be added or deleted or modified from outside the object. Here's an example to demonstrate it:
let spaceship = { 'Fuel Type' : 'Turbo Fuel',homePlanet : 'Earth',
color: 'silver',
'Secret Mission' : 'Discover life outside of Earth.'
};
spaceship.color = 'glorious gold' //Sets value of color property as 'glorious gold'
spaceship.numEngines = 2 //Creates a property numengines and assignes the value=2
delete spaceship['Secret Mission'] //Deletes the Secret Mission property from spaceship
NOTE: Objects are mutable, i.e., we can change their properties even when they are declared with 'const'.