How to Use String and Math Methods in Object-Oriented JavaScript?

Estimated read time 1 min read

In object-oriented JavaScript, you can use string and math methods by either creating instances of built-in objects (e.g. String or Math) or by adding methods to custom objects.

Examples:

String methods:

const name = new String("John Doe");
console.log(name.toLowerCase());  // "john doe"

// or

const person = {
  name: "John Doe",
  getNameLength: function() {
    return this.name.length;
  }
};
console.log(person.getNameLength());  // 8

Math methods:

const num = Math.PI;
console.log(Math.round(num));  // 3

// or

const circle = {
  radius: 5,
  getArea: function() {
    return Math.PI * Math.pow(this.radius, 2);
  }
};
console.log(circle.getArea().toFixed(2));  // 78.54

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply