What is a Method in JavaScript

As we've discussed before, it is possible for you to put a function inside an object, which is often referred to as a method.

javascript
1let user = {
2  firstName: "John",
3  lastName: "Doe",
4  printUserName: function () {
5    console.log("John Doe");
6  },
7};
8
9user.printUserName();

There is a shorter syntax for writing methods. It allows you to omit the function keyword.

javascript
1let user = {
2  firstName: "John",
3  lastName: "Doe",
4  printUserName() {
5    console.log("John Doe");
6  },
7};
8
9user.printUserName();
text
1John Doe

In this case, the printUserName() function will print the user's name to the console.

However, notice that in this example, we hardcoded the user name. That is not a good practice. If you want to change the user's name, you'll also have to change the corresponding printUserName() method.

A better way to code is to use the properties firstName and lastName inside the printUserName() method.

javascript
1let user = {
2  firstName: "John",
3  lastName: "Doe",
4  printUserName: function () {
5    console.log(`${user.firstName} ${user.lastName}`);
6  },
7};
8
9user.printUserName();
text
1John Doe

Wait, there is more!

You need an account to access the rest of this lesson. Our course is 50% off for limited time only! Don't miss the opportunity!

🎉 Create an Account 🎉