Learn Javascript Object Methods with examples

Objects in JavaScript are collections of key/value pairs. The values can consist of properties and methods and may contain all other JavaScript data types, such as strings, numbers, and Booleans.

toString() 

The toString() method takes no arguments; it returns a string that somehow represents the value of the object on which it is invoked.

JavaScript invokes this method of an object whenever it needs to convert the object to a string. This occurs, for example, when you use the + operator to concatenate a string with an object or when you pass an object to a method that expects a string.

        
let point = {
x: 1,
y: 2,
toString: function() { return `(${this.x}, ${this.y})`; }
};

console.log(point.toString())

// Output : (1, 2)         
    

toLocaleString()

The JavaScript Number toLocaleString() method returns a string with a language-sensitive representation of this number. The purpose of this method is to return a localized string representation of the object. The default toLocaleString() method defined by Object doesn’t do any localization itself: it simply calls toString() and returns that value.

        
let number = 500000;
console.log(number.toLocaleString());   //  Output : 500,000

let number1 = 875643.789;
console.log(number1.toLocaleString("en-IN"));  //  Output : 8,75,643.789

let currency = number1.toLocaleString("de-DE", {
  style: "currency",
  currency: "EUR",
  maximumSignificantDigits: 6,
});

console.log(currency);   // Output : 875.644 €           
    

valueOf()

The valueOf() method is much like the toString() method, but it is called when JavaScript needs to convert an object to some primitive type other than a string—typically, a number. JavaScript calls this method automatically if an object is used in a context where a primitive value is required.

        
let point = {
x: 4,
y: 5,
valueOf: function() { return Math.hypot(this.x, this.y);
}
};

console.log(point.valueOf());

// Output : 6.4031242374328485            
    

toJSON()

In JavaScript, the JSON.stringify() function looks for functions named toJSON in the object being serialized. If an object has a toJSON function, JSON.stringify() calls toJSON() and serializes the return value from toJSON() instead.

        
        
x = {a:5, b:{c:[false,null,""]}}; // Define a test object
y = JSON.stringify(x);            
z = JSON.parse(y); 
               
console.log(y); 	

// Output : {"a":5,"b":{"c":[false,null,""]}}             
    
Posted in

Ankit Patel

Leave a Comment

Your email address will not be published.

Scroll to Top