DEV Community

Cover image for JavaScript Object Methods
karthika jasinska
karthika jasinska

Posted on

JavaScript Object Methods

What are Object Methods?
Methods are actions that can be performed on objects.
Methods are functions stored as property values.
In a method, 'this' refers to the owner object.

Syntax:
objectName.methodName()

// Object creation

Example:

let student = {
name: "Karthika",
class: "12th",
section: "A",

studentDetails: function () {
    return this.name + " " + this.class
        + " " + this.section + " ";
}
};
Enter fullscreen mode Exit fullscreen mode

// Display object data
console.log(student.studentDetails());
Output:
Karthika 12th A
If we given methodname without()brackets,its return the function definition,
console.log(student.studentDetails);
Output:
[Function: studentDetails]

Explanation:"this" Keyword
In the example above, this refers to the student object.

this.name means the name property of the student object.
this.class means the class property of the student object.
this.section means the section property of the student object.

Using Object.values()
Object.values() creates an array from the property values:

const person = {
  name: "Karthi",
  age: 30,
  city: "New York"
};

// Create an Array from the Properties
const myArray = Object.values(person);
let text = myArray.toString();//we will discuss later
console.log(text);

Output:Karthi,30,New York 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)