Welcome to the third day of the challenge. Today's area of discussion and understanding would be on Objects. It might be clear by now that we will be using codepen.io as our javascript editor.
What are Objects?
Variables are used to store some form of data into them. However, you can only store one kind of data in a variable and that's a bummer. Unlike variables, objects are used to store multiple values. Consider an object to be a bike, a bike is made up of various parts(values) such as wheels, engine, brakes, etc. All those parts constitute a bike. Similarly, all the values constitute an object.
Declaring an Object.
It is easy to declare an Object.
let bike = {
name: "BMW",
wheels: 2,
colour: "white"
}
In the above code, we declared an object bike and inside it declared new variables(name, wheels, colour). As you can see declaring an object for a group of variables makes more sense as now we know that each variable will be related to the object inside which they were declared.
Accessing the object.
Now in order to access a variable enclosed inside an object just call out the object, followed by a period and the name of the variable
let bike = {
name: "BMW",
wheels: 2,
colour: "white"
}
// To access the variable wheel
bike.wheels
Functions inside Objects.
Another reason why functions are more widely used is because we can even include Functions inside Objects. As we have already seen we need to add a function before declaring any function. However, while declaring it inside an object we don't need to write the function keyword. Let's add a function start to our code above:
let bike = {
name: "BMW",
wheels: 2,
colour: "white"
start(){
alert("You have ignited the engine")
}
}
Calling out a function is no different from calling a variable as we have seen above. To call a function:
bike.alert()
NOTE -> A Function inside an object is referred to as Method.
You can also nest an object inside another object to have a piece of deeper information inside it
let bike = {
name: "BMW",
wheels: 2,
colour: "white"
number:{
production_no: 4563
unit_no: 79
batch: 3
}
}
//To access batch just type the following
bike.number.batch