0

I want to see the value of obj,following code is used

var obj = { 
            x: 'abc',
            y: 2,
            z: 3 
                   };

When I use alert(obj) it just gives me [object Object]. When I use console.log(obj) it shows the object in console correctly

why this alert function cant shows the object as it is...???

is there anymore data types that alert function cant show correcly

3
  • 2
    alert converts object to string.. you can add toString method to your object - like this jsbin.com/yofibe/1/edit Commented Dec 9, 2014 at 17:37
  • 1
    alert() accepts string argument, so not sure what you are expecting. What is wrong with using console.log() that is preferred method for getting at debug information. Commented Dec 9, 2014 at 17:38
  • alert(toString.call(obj)); is essentially what you are seeing. Commented Dec 9, 2014 at 17:39

3 Answers 3

2
   alert(JSON.stringify(obj))

returns a string of the property names and their values of an object.

Sign up to request clarification or add additional context in comments.

1 Comment

Make sure to test for JSON object in browsers first before simply using this. This will break in IE8 or lower.
1

Alert's message parameter:

message is an optional string of text you want to display in the alert dialog, or, alternatively, an object that is converted into a string and displayed.

https://developer.mozilla.org/en-US/docs/Web/API/Window.alert

Since it convert everything to strings, it means it uses object.toString() method which returns [object Object]. There are many ways to format the output (see @kennebec's answer), but you can also override its toString method.

Here's a simple example of overriding it into a nicely formatted string:

var obj = {
  x: 'abc',
  y: 2,
  z: 3
};

Object.prototype.toString = function() {
  var output = "";
  for (var i in this) {
    output += i + ": " + this[i] + "\n";
  }
  return output;
}

alert(obj);

Comments

-2

Use

console.log(obj)

to display objects in a modern browser. If you're using Chrome, press Shift+Ctrl+J or F12 to then see the console.

Alerts simply display either strings or variables that can be cast as strings (long, float, integer). Alert cannot display any object, including arrays nor can it display pure JSON/XML or DOM elements. Just be careful with backwards compatibility because console.log() will break javascript in IE8 (Windows XP). There are other javascript tests you can perform to test for IE8 compatibility before calling your console.log() command.

1 Comment

Downvotes are likely because it does not address the question, in which the OP mentions that they see the output they expected from alert(obj) in console.log(obj).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.