1

I'm trying to take an array object and change its print representation - just of that object, not of all arrays in the program. I hoped setting the toString property would do the job, but it doesn't:

var a = [1, 2, 3]

// Prints using the default representation
console.log(a)

// Try to override toString
a.toString = function() {
  return 'some new representation'
}

// Still uses the default representation
console.log(a)

What am I missing?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
rwallace
  • 31,405
  • 40
  • 123
  • 242
  • 3
    The `console.log()` code does what it wants. Overriding `.toString()` will work when the array is coerced to a string value, but `console.log()` doesn't necessarily do that unless you force it to. – Pointy Apr 21 '17 at 12:22
  • Duplicate of http://stackoverflow.com/questions/9943257/how-do-i-override-the-default-output-of-an-object – mplungjan Apr 21 '17 at 12:28
  • Check the link [link](http://stackoverflow.com/questions/6307514/is-it-possible-to-override-javascripts-tostring-function-to-provide-meaningfu), you can see how to do that properrly ; – eisbach Apr 21 '17 at 12:29

1 Answers1

1
var a = [1, 2, 3];

// Prints using the default representation
console.log(a);

// Try to override toString
a.toString = function() {
  return 'some new representation'
}

// append blank string to invoke toString function
console.log(""+a);
Julian
  • 33,915
  • 22
  • 119
  • 174
Anurag Dadheech
  • 629
  • 1
  • 5
  • 14