By the end of this lesson, you will be able to:
:information_source: Info Object Definition An object is like a container that holds related information together. Think of it as a box with labeled compartments - each compartment (property) has a name and can store different things (values).
An example of object in real life:
var studentCard = {
name: ["John", "Doe"],
image: "image.png",
program: "D",
intake: 2021
};
This is a student card. The name, image, program and intake year are called properties. Every student card has these properties.
Every student has different values but will still have the same properties. Each student will have their unique name, image, specific program and intake year.
JavaScript objects are variables that contain multiple data values.
Each property has a value. The values can be of any data type such as Strings, Numbers, Boolean and even Functions (methods).
var myObject = {
fruits: ["Banana", "Apple", "Orange"],
numbers: 360,
string: "Hello World",
boolean: true,
method: () => {
return "This is a function.";
}
};
After the object is created, we can access the properties and methods of the object with simple syntax:
script.js | Output |
---|---|
myObject.fruits |
["Banana", "Apple", "Orange"] |
myObject.fruits[0] |
Banana |
myObject.numbers |
360 |
myObject.string |
Hello World |
myObject.boolean |
true |
myObject.method() |
This is a function. |
The general syntax that made up an object:
var objectName = {
name1: value1,
name2: value2,
name3: () => {
// function for object to do something
}
};
Important rules:
Going through the above examples, you are probably wondering about the object dot notation such as myObject.fruits
because it looks very familiar.
That's because every time you use DOM or any other methods, you are actually working with JavaScript objects.
Using methods available on the document object:
var myDiv = document.createElement('div');
Accessing properties available on p1 object:
var p1 = document.querySelector('p');
p1.textContent = "This is a paragraph.";
Using methods available on the console object:
console.log("Hello World");
Using methods available on the Math object:
Math.random();
Objects are fundamental to JavaScript programming:
Concept | Description | Example |
---|---|---|
Property | A name-value pair that stores data | car.color = "red" |
Method | A function that belongs to an object | car.start() |
Dot Notation | Way to access object properties/methods | object.property |
Object Creation | Define objects using curly braces | var obj = { key: value } |
Objects allow you to group related data and functions together, making your code more organized and easier to work with.