Object Methods | JavaScript 🔥 | Lecture 041

The Coding Classroom
7 Apr 202323:05

Summary

TLDRThe lecture discusses adding functions called methods to JavaScript objects, allowing objects to have capabilities beyond just storing data. Methods are created by assigning a function expression as an object property value. The 'this' keyword gives methods access to other data in the object. An example method called calcAge() calculates a person's age from their birth year. Another method getSummary() returns a string summarizing the person's data. This demonstrates that arrays are also objects that have built-in methods, foreshadowing more complex topics ahead about why arrays can have methods.

Takeaways

  • 😀 Objects can contain functions as values, called methods
  • 👍 Methods can access the object's properties using the 'this' keyword
  • 💡 'this' refers to the object calling the method
  • 📝 Methods can calculate and store data in the object for later use
  • 🚦 Arrays are actually a special type of object with built-in methods
  • 🔑 Writing methods keeps code DRY by avoiding repetition
  • ✏️ Challenges help reinforce learning of new concepts
  • 🎯 Object methods enable efficient data access and manipulation
  • 🚀 There is an exciting programming journey ahead to dive deeper
  • 🧠 Understanding function expressions enables writing methods

Q & A

  • What are object methods?

    -Object methods are functions that are attached to an object. They are also called method properties on objects.

  • How do you add a method to an object in JavaScript?

    -To add a method to an object, you define a function expression as the value for a property in the object. The property name is the name of the method and the function expression becomes the method definition.

  • What is the 'this' keyword in a method?

    -The 'this' keyword in a method refers to the object on which the method is being called. So 'this' points to the object calling the method.

  • Why use the 'this' keyword instead of hard-coding the object name?

    -Using the 'this' keyword allows the code to work automatically if the object name changes, following the DRY (Don't Repeat Yourself) principle by avoiding hard-coding the name.

  • How can an object method access other properties on the same object?

    -By using the 'this' keyword, a method can access other properties defined on the same object, for example with 'this.propertyName'.

  • What are built-in array methods?

    -Built-in array methods are functions that allow manipulation of arrays, like push(), pop(), shift(), unshift() etc. Arrays have these because arrays are also objects.

  • What is method chaining?

    -Method chaining is calling one method after another sequentially by chaining them together with the dot notation, for example array.push().pop().

  • Should calculation logic go directly in object property values?

    -No, any complex logic should go in methods instead, while property values can cache results, avoiding repeat calculations.

  • Why define a getSummary() method instead of a summary property?

    -Defining a getSummary() method allows dynamically generating the summary string when needed, ensuring it stays up-to-date if properties change.

  • What is the main advantage of using OOP in JavaScript?

    -The main advantage of OOP in JavaScript is better organization by grouping related properties and behaviors into objects, keeping code modular and reusable.

Outlines

00:00

😀 Adding Functions to Objects as Methods

Introduced the concept of adding functions to objects as methods. Showed how to attach a function calcAge() to the Jonas object as a method to calculate his age. Demonstrated how the this keyword allows accessing the object properties like birthYear from inside the method.

05:01

😯 Using this Keyword to Reference the Calling Object

Explained that the this keyword inside a method points to the object calling the method. Showed how we can use this to reference properties of the calling object like birthYear instead of passing them as arguments. Discussed why this is better than hardcoding the object's name.

10:03

💡 Storing Values in the Object for Efficiency

Demonstrated how we can use this to not just reference properties but also set new properties on the object. Calculated age once using calcAge() and stored it in this.age property to avoid repeat calculations. Retrieved the stored age property later instead of recomputing.

15:03

👨‍💻 Writing a Method to Summarize Object Data

Gave a coding challenge to practice writing a method getSummary() that returns a string summarizing the person data in the object. Used techniques like this, calcAge() and ternary operator to access properties and build the summary string.

20:03

🔗 Linking Object Methods to Array Methods

Built a bridge between object methods and array methods by explaining that arrays are also objects behind the scenes. This allows arrays to have built-in methods that manipulate them.

Mindmap

Keywords

💡object

An object in JavaScript is a collection of key-value pairs that can hold different types of values. Objects are very useful for organizing data and functionality together. In the video, the example object used is 'Jonas' which contains properties like birthYear, job, etc.

💡method

A method is a function that is attached to an object. Since functions are values in JavaScript, they can be added as properties on objects. Methods allow objects to have reusable functionality that is tied to the data in the object. For example, the calcAge() method is attached to the Jonas object.

💡this

The 'this' keyword refers to the object on which a method is called. Inside a method definition, 'this' points to the calling object. So inside calcAge(), 'this' refers to the Jonas object since that is where calcAge() is called using the dot notation.

💡function expression

A function expression produces a function value without needing a function name. This is required when assigning a function as a value to a property, like with methods. Only expressions, not declarations, can be used in this way.

💡template literal

Template literals use backticks and allow embedding expressions directly inside strings. They are very useful for building strings from mix of literal text and data, like in the getSummary() method example.

💡this.property

Using 'this' gives access to properties on the calling object. So this.birthYear inside calcAge() refers to the birthYear property on the Jonas object.

💡dot notation

The dot notation is used to access properties and methods on an object, like jonas.calcAge(). The part before the dot is the object, and after is the property/method name.

💡DRY principle

DRY stands for Don't Repeat Yourself. It's a principle for writing cleaner code by having each piece of data stored in a single place, instead of duplicated.

💡turnery operator

The turnery operator provides a shortcut for if/else statements. It has a condition, and returns one value if truthy and another if falsy. It is used in getSummary() to return 'a' or 'no' based on the license property.

💡arrays are objects

Arrays have built-in methods like push() and pop() that can be called on them. This is because arrays are actually a specialized type of objects behind the scenes.

Highlights

Objects can hold different types of data like strings, numbers, Booleans, arrays, and even other objects

Functions are values, so we can create a key-value pair where the value is a function - this is called a method

Any function attached to an object is called a method

The this keyword points to the object calling the method

Using this avoids violating the DRY principle by not hardcoding the object's name

Can use this to store calculated values as properties on the object

Writing a method to return a summary string about the object's data

Arrays are also objects, which is why they can have built-in methods like push(), pop(), etc.

Creating own methods on own objects vs using built-in methods on arrays

Understanding that arrays are objects and have methods is an important realization on the development journey

Can hold different data types like strings, numbers, Booleans in one object

Functions are first-class citizens - can be passed around like values

Methods allow accessing functionality through dot notation

This keyword gives access to current object from within methods

Getters encapsulate access and hide implementation details

Transcripts

play00:01

Let's keep exploring objects

play00:03

and this lecture will bring us to object methods.

play00:08

So we learned that objects just like a race

play00:11

can hold different types of data.

play00:14

And they can hold even a race,

play00:16

and in fact, they could even hold objects inside objects.

play00:20

But now we can take it even further.

play00:23

And for that, remember how I said

play00:25

that functions are really just another type of value.

play00:29

And if a function is just a value

play00:31

then that means that we can create a key value pair

play00:35

in which the value is a function.

play00:37

And that then means that we can in fact,

play00:40

add functions to objects.

play00:43

And so let's now see how.

play00:45

And once more, I will get back this object here

play00:50

but we will change it up a little bit this time around.

play00:55

So here let's simplify and just put the birthYear.

play01:00

So just 1991.

play01:03

And I also want to add a Boolean here, hasDriversLicense.

play01:10

Just to show you that we can hold all kinds

play01:14

of different data types in one object.

play01:17

But now let's also add a function here as a key value pair.

play01:22

So to do that, all we have to do is to add another key here.

play01:27

And the function that we want to add is again,

play01:29

the calcAge function.

play01:32

So that's one of the favorites, as you can see,

play01:35

but it is because it's a very simple calculation

play01:38

that we can do with the birth year.

play01:41

So to do that, let's simply add the name

play01:43

basically off the function here as a key.

play01:47

So as a property,

play01:48

so calcAge and then the colon, and now here

play01:53

we simply specify the function as an expression

play01:56

and that works because the expression produces the value.

play02:00

And so we can just do this,

play02:03

so function, and just like before ,

play02:06

we pass in the birth year

play02:10

and we return 2037 minus the birth year that was passed in.

play02:19

So this is pretty similar to simply writing this, right?

play02:24

So a regular function expression.

play02:27

So const calcAge like this,

play02:30

this is how we used to do it before.

play02:32

And so you see that this is pretty similar.

play02:34

The difference is just in the syntax

play02:36

because now calcAge is not a regular variable like here,

play02:41

but it's a property of the Jonas object.

play02:43

And so therefore we use the colon here

play02:46

but the rest here is exactly the same.

play02:48

And so that's why it was very important

play02:50

that you understood what a function expression actually is

play02:54

because here we need to function expression

play02:57

to create this method.

play02:59

And that's what this function is called.

play03:02

So any function that is attached

play03:04

to an object is called a method.

play03:07

So of course we could have not used

play03:10

a function declaration here.

play03:12

So something like this,

play03:15

so function calcAge, for example, that would not work,

play03:20

we would certainly get an error here.

play03:23

So unexpected token function,

play03:26

because this is a declaration.

play03:27

And so it doesn't work here,

play03:29

here, we need an expression.

play03:31

And so this will work indeed.

play03:34

Okay? Does this make sense?

play03:36

So if you can think of functions as simply being values

play03:41

then you can see that a method is actually also a property.

play03:46

It just happens to be a property

play03:47

that holds a function value.

play03:50

So here we have a string value,

play03:52

here we have an array value,

play03:55

here we have a Boolean value,

play03:56

and here we have a function value.

play04:00

All right.

play04:01

So, I hope that's logical.

play04:04

And now just like we can access any other property,

play04:08

we can also access the calcAge property or method.

play04:13

So jonas.calcAge and so calcAge is now the function value,

play04:19

and just like any other function in order to call it,

play04:22

we use the parenthesis.

play04:24

And now we can pass in the year here.

play04:27

And so that should then calculate our age.

play04:31

And let's just unlock this result to the console here,

play04:38

just to see if everything works.

play04:41

And it does indeed.

play04:44

Okay. And you could also have access

play04:48

to this method using the bracket notation,

play04:52

because again, it's just as if it was a normal property

play04:57

and the brackets would actually be necessary here

play05:01

so that this then here is the function

play05:03

and then we call the function using the parenthesis.

play05:08

So let's try that.

play05:10

And, yeah, here this needs to be a string.

play05:16

So like I showed you in the last lecture,

play05:19

and now here we get 46 as well.

play05:22

Okay. So just like I showed you in the last video

play05:26

with the operator proceedings table,

play05:28

the first thing that happens here,

play05:30

is that jonas.calcAge is computed.

play05:33

And so this here will become the function value.

play05:36

And then with the parenthesis,

play05:38

we call that function value here and passed in 1991.

play05:42

And the same thing here,

play05:44

so here we access the property calcAge using the brackets

play05:48

and then this here will basically be replaced

play05:51

with the function,

play05:52

and then we call the function right here, just like before.

play05:58

All right, now you might have noticed

play06:01

that the birth year 1991,

play06:05

that we passed here as an argument to the method

play06:07

is actually already defined

play06:09

in the Jonas object itself up here, right?

play06:14

So we already have this information in the Jonas object.

play06:18

And so writing the same number here and here is not ideal

play06:22

because we might make a mistake and pass in the wrong year.

play06:26

For example, right here.

play06:28

So Jonas' birth year is 91

play06:31

but here, we could, for some reason accidentally do 92

play06:35

and then it would be wrong.

play06:37

And even if we do not make any mistake,

play06:40

this is still not ideal

play06:42

because we are not keeping the code dry.

play06:45

So we're violating the don't repeat yourself principle.

play06:49

So if we know the birth year of Jonas,

play06:51

it would only be written in one place,

play06:54

not in multiple places,

play06:55

because if that might change,

play06:57

then we have to change it everywhere.

play06:59

That's always the philosophy that we need to keep in mind.

play07:03

So what if we could actually access this birth year property

play07:07

directly from the Jonas object

play07:10

instead of having to pass it in?

play07:12

Well, it turns out that we actually can,

play07:16

and that's because in every method,

play07:18

JavaScript gives us access

play07:20

to a special variable called this.

play07:24

And so what we can do now is in this calcAge function,

play07:28

we can read the birth year directly

play07:30

from this object itself without having to pass it in

play07:33

as a parameter here into this function.

play07:38

Alright, so let me copy this and comment this one out

play07:42

just so that we keep a record of what we did

play07:46

but this here will be the new version.

play07:50

So now we no longer need this parameter

play07:53

and we will read the birth year directly from the object.

play07:58

And for that again, we will use the this keyword.

play08:02

So the this key word

play08:03

or the this variable is basically equal to the object

play08:08

on which the method is called,

play08:10

or in other words,

play08:12

it is equal to the object calling the method.

play08:15

So, let's see who is calling the method.

play08:19

So down here, here is calcAge,

play08:22

and the object that is calling the method is Jonas,

play08:26

because that's where the dot is.

play08:28

And let's forget about this one,

play08:30

actually comment it out here.

play08:32

And so again

play08:34

the object that is calling the calcAge method here is Jonas.

play08:38

And so that means that inside this method

play08:42

the this variable or the this keyword will point to Jonas.

play08:47

And so let me just write this.birthYear here

play08:51

and then I can explain it even a little bit better.

play08:55

So, here we don't need to pass the 1991 here

play09:00

and I will run this now and we still get the correct result.

play09:05

So, great.

play09:07

And to make this even more clear here,

play09:11

let's also log this to the console,

play09:17

and indeed, this is the whole Jonas object.

play09:21

And so again, that's because the Jonas object

play09:25

is the one who is calling this method,

play09:27

so this function,

play09:29

see here, it's jonas.calcAge

play09:33

and so whatever appears before the dot

play09:35

is the one who is calling the method.

play09:37

And so therefore, in the method,

play09:40

this points to Jonas now,

play09:43

and if this points to Jonas,

play09:45

then this.birthYear is of course

play09:48

this value that we have right here.

play09:51

Great.

play09:52

So you see that the this keyword

play09:54

is something really, really useful

play09:56

and we will learn even more about the this keyword

play09:59

in greater detail in a later section.

play10:02

For now, I just wanted to introduce you to this concept

play10:06

and I noticed can be a bit confusing.

play10:09

So really make sure to maybe pause the video

play10:12

and really analyze what's happening here.

play10:16

Maybe you can even rewind a little bit

play10:18

and hear my explanation again,

play10:20

that might be useful too.

play10:22

Now you might argue that maybe we don't even need

play10:25

this confusing this keywords.

play10:27

Why not just do jonas.birthYear, here instead?

play10:32

Well, because that would actually still violate

play10:35

the don't repeat yourself principle.

play10:38

It would work just the same here now,

play10:40

but then let's say

play10:41

that we need to change the name of the object.

play10:44

So we change it here to Jonas2

play10:47

and then we call Jonas2 down here,

play10:49

and then the code will no longer automatically work,

play10:53

because now Jonas is not defined of course.

play10:57

And so we would have to keep that in mind

play10:59

and then come here and manually change this as well,

play11:02

while if we had the this keyword,

play11:05

then everything will keep working

play11:07

without us having to change it there,

play11:09

because now this will simply point to Jonas2,

play11:13

because that is the object calling the method.

play11:16

And so therefore it's always a good idea

play11:19

to reference the object itself

play11:22

and not hard-code the name of the object.

play11:25

So let's put it back to Jonas and yeah, much better.

play11:33

So this works great already,

play11:35

and we're really going

play11:36

into some more advanced territory here.

play11:39

So I hope you're still following me

play11:41

and you're still making sense of everything.

play11:44

However, we can actually even take this a little bit further

play11:49

but don't worry, it's not going to get a lot more confusing,

play11:53

just a small variation of this,

play11:55

because let's say that we need to access

play11:57

the age multiple times throughout our program.

play12:02

So that would be like calling this a couple of times.

play12:07

So let's say in three places of our application,

play12:10

we need to access the age,

play12:12

and so, of course this will work,

play12:16

and indeed it does.

play12:18

And it always locks the Jonas object

play12:21

because we still have this here.

play12:24

So this makes it a bit easier to view.

play12:27

And so what happens here

play12:29

is that a function will get called a total of four times.

play12:33

And so this computation here will be done four times.

play12:37

And in this case that's not a big deal

play12:39

but it might be a like a heavier computation

play12:42

that actually takes some more time,

play12:45

and so it would be a bad practice to do this multiple times.

play12:49

Instead, what we can do is to just calculate the age once,

play12:53

then store it in the object,

play12:55

and then when we need it at a later point,

play12:58

we can then just retrieve the age

play13:00

as a property from the object.

play13:02

So, I hope you're following me here.

play13:07

So I will again copy this and comment it out

play13:10

so that we keep all the three versions that we did here.

play13:14

So, what I was trying to say

play13:16

is that we can now use the this keyword

play13:19

also to store a new property.

play13:22

So, we can say this.age is equal to this here.

play13:31

So we calculate the age,

play13:33

and then we create a new property on the current object.

play13:37

So in this case, on the Jonas object,

play13:40

and remember that we can use the dot notation like this

play13:43

to create new properties.

play13:46

So we did that in a previous lecture as well.

play13:51

Where was that?

play13:53

Yeah, right here.

play13:54

So here we created jonas.location

play13:56

and set it to Portugal.

play13:58

And so here we are essentially creating jonas.age

play14:02

and setting it to this age that we just calculated.

play14:06

And then we can simply return this age.

play14:09

And of course we don't even need to return anything

play14:13

if we didn't want to.

play14:14

We could make this method only calculate the age

play14:17

but not even return it,

play14:19

but I think it's a good practice

play14:21

to actually also return it.

play14:23

And so now here we can replace the function call

play14:26

with simply a request

play14:28

for the age property,

play14:31

and notice this trick that I did here again

play14:33

with the command D, right,

play14:35

So this gives me multiple cursors

play14:38

and then I can do one operation

play14:40

in multiple places at the same time.

play14:42

So that's a really handy shortcut.

play14:44

So, again, command D, or control D

play14:48

and in the menu bar that means add next occurrence.

play14:53

So let's test this and the results should be the same,

play14:58

and it is, but we only needed to calculate the age once

play15:02

then from here,

play15:04

we simply retrieve the property

play15:05

that we had already calculated before.

play15:08

And so this is the most efficient solution let's say.

play15:13

All right, and now I actually have another,

play15:15

a small challenge for you

play15:17

that you can do just in this video.

play15:20

So I want you to write a method called getSummary

play15:24

and this method should return a string

play15:26

which should kind of summarize the data about Jonas,

play15:30

or, of course, any other person data

play15:33

that you might have used.

play15:36

For example,

play15:38

let me again,

play15:41

actually we can get rid of this.

play15:43

So let me write Challenge here again

play15:46

and then do an example string.

play15:49

So I want you to write for example this,

play15:52

Jonas is a 46 year old teacher.

play16:01

And we now could actually add all the data here

play16:03

to the string,

play16:04

but that would be too much work

play16:07

and I'm a bit lazy now.

play16:08

So let's just also say if I have a driver's license or not.

play16:13

So Jonas is a 40 year old teacher

play16:16

and he has a driver's license.

play16:23

And it says that I have a driver's license

play16:26

because it hasDriversLicense is true

play16:30

but if it was false, then here, it should say

play16:33

and he has no driver's license.

play16:37

So it's either a or no.

play16:40

So figure out how you can do that,

play16:42

and so I hope you manage to do it.

play16:45

It's a bit similar to what we did in the previous lecture

play16:48

but this time I want you to actually write a method

play16:51

on your own.

play16:52

So give this a try and I see you here in a second.

play16:58

Okay. So let's add getSummary

play17:05

and remember that you to a need to have a comma

play17:07

between the properties.

play17:09

And so that's true also with methods,

play17:11

so here we need a comma,

play17:14

and then just a function

play17:19

and it will then get all this data of course,

play17:21

from the current object.

play17:24

So actually let's first call this method,

play17:28

so, and we're doing it inside of console log,

play17:31

log because of course,

play17:33

we want to be able to see the summary string

play17:36

as a message in the console.

play17:38

So jonas.getSummary.

play17:44

Okay. So, which is the object calling the method?

play17:48

It is Jonas.

play17:50

And so therefore, the this keyword inside of getSummary

play17:54

will be Jonas.

play17:55

So I hope that this one is clear at this point.

play18:00

So let's now build a string here,

play18:03

and starting with the name,

play18:05

it is at this.firstName is a,

play18:14

and now the age,

play18:16

so this, and now what do we do here?

play18:21

Should we use the age property, or should we do calcAge?

play18:26

Well, I would say that we should do calcAge

play18:29

because we cannot assume that calcAge

play18:31

was already called before.

play18:35

Okay.

play18:35

And if we don't call calcAge before we call getSummary

play18:39

then the age property would not exist.

play18:43

And so,

play18:45

and so it's, it's better to actually do calcAge here.

play18:52

And so I think we did this before,

play18:55

so in a template string, we can easily do a function call.

play18:59

That's not a problem at all.

play19:01

So this.calcAge will call this other method

play19:05

and this will then return the age.

play19:11

Alright. And maybe it might be strange for you

play19:14

to call the function also on this,

play19:17

but well, the rule is just exactly the same.

play19:20

This is Jonas in this object,

play19:23

and so this is essentially the same as writing it here.

play19:29

Alright. So this will become the age

play19:32

and so, year old,

play19:37

and now the job, jonas.job,

play19:41

and he has,

play19:43

and now we need to decide between a and no.

play19:47

So let's do a turnery operator here.

play19:50

So we get this.DriversLicense,

play19:56

and basically if it's true

play19:58

then we want the results of this operator to be a,

play20:03

and if not, we want it to be no.

play20:07

And then driver's license.

play20:12

Okay? Makes sense?

play20:14

So again, here we want either a or no,

play20:19

depending on the state of the hasDriversLicense property.

play20:24

So we get that property

play20:26

by calling this.hasDriversLicense

play20:29

and here we're using the turnery operator.

play20:32

And so if this first part is true

play20:34

then the result of the operator will be a,

play20:37

and otherwise the result will be no.

play20:40

And so that's what will then be put

play20:42

into this place of the sentence.

play20:46

Okay. And we already called the method down here

play20:51

and we logged it to the console,

play20:53

and so I think this should work now.

play20:56

And it does.

play20:58

So Jonas is a 46 year old teacher

play21:01

and he has a driver's license.

play21:03

Now just to test, let's set it to false and no,

play21:09

and he has no driver's license.

play21:12

Beautiful.

play21:16

Okay.

play21:19

And yeah, that's all the code

play21:21

that I had to show you in this video.

play21:24

And now just to finish the lecture,

play21:26

which I know is already running quite long,

play21:29

but I want to basically build a bridge

play21:31

between this method and the array method lecture.

play21:36

So remember that we used methods on a race previously,

play21:40

so we can quickly go there.

play21:43

So it was before this challenge.

play21:47

Yes, indeed.

play21:49

So for example here we have friends.push.

play21:52

And so we have an array and on there we call a method.

play21:56

So just like we did in this video,

play21:59

now what this means is

play22:01

that arrays are actually also objects,

play22:04

they are just a special kind of object.

play22:07

And so they have functions, or in other words

play22:09

they have methods that we can use to manipulate them

play22:13

like push, pop, shift and unshift and many more.

play22:19

All right? So in this lecture,

play22:21

we created our own methods on our own objects.

play22:24

But here we basically used built in methods on a race.

play22:28

And so once again that means

play22:30

that the race are actually also objects,

play22:34

that's why they can have methods as well.

play22:38

And we will dive deeper into why things work like this,

play22:42

but I wanted you to realize this early on in the course,

play22:46

this is quite a complex topic,

play22:48

and so there is really a very exciting journey

play22:52

still ahead of you.

play22:53

So I hope you're enjoying this journey so far.

play22:56

And now to test your knowledge,

play22:58

there is coding challenge number three, coming up next.