Related
I am trying to alert a returned value from a function and I get this in the alert:
[object Object]
Here is the JavaScript code:
<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible());
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
</script>
whichIsVisible is the function which I am trying to check on.
As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?
That is because there are different types of objects in Javascript!
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
… several more …
and Object objects!
stringify({}) -> [object Object]
That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
The default conversion from an object to string is "[object Object]".
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.
Sidenote: IDs should not start with digits.
[object Object] is the default toString representation of an object in javascript.
If you want to know the properties of your object, just foreach over it like this:
for(var property in obj) {
alert(property + "=" + obj[property]);
}
In your particular case, you are getting a jQuery object. Try doing this instead:
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible().attr("id"));
});
This should alert the id of the visible element.
You can see value inside [object Object] like this
Alert.alert( JSON.stringify(userDate) );
Try like this
realm.write(() => {
const userFormData = realm.create('User',{
user_email: value.username,
user_password: value.password,
});
});
const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
Alert.alert( JSON.stringify(userDate) );
reference
https://off.tokyo/blog/react-native-object-object/
Basics
You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.
string, number, boolean, null, undefined, and symbol.
In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
If primitives have no properties, why does "this is a string".length return a value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
By this means primitives have access to all the properties (including methods) defined by their respective object constructors.
So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.
Analysis of toString() method
Consider the following code
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.
But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?
Closer look at Object.prototype.toString()
As per the documentation,
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Understand this from the following example
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
References:
https://es5.github.io/x15.2.html#x15.2.4.2
https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
It's the value returned by that object's toString() function.
I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:
function whichIsVisible_v2()
{
if (!$1.is(':hidden')) return '#1';
if (!$2.is(':hidden')) return '#2';
}
That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.
[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
I think the best way out is by using JSON.stringify() and passing your data as param:
alert(JSON.stringify(whichIsVisible()));
You have a javascript object
$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...
you have to treat $1 and $2 like jQuery objects.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".
Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.
The object whose class is Object seems quite different from the usual class instance object, because it acts like an associative array or list: it can be created by simple object literals (a list of keys and properties), like this: let obj={A:'a',B:'b'}; and because it looks very like this same literal notation when displayed in the Developer Tools Console pane and when it is converted to a JSON string.
But, in fact, the only real difference in objects of other classes (which are derived or extended from Object) is that other classes usually have constructors and methods (these are all functions), in addition to properties (which are variables). A class instance object is allocated using the 'new' operator, and its properties and methods are accessible through the 'this' variable. You can also access the underlying static functions that are copied to each new instance by using the 'prototype' property, and even extend system classes by adding new functions to their prototype object.
The Array object is also derived from Object and is frequently used: it is an ordered, 0-indexed array of variable values.
Object objects, unlike Arrays and other classes are treated simply as associative arrays (sometimes considered ordered, and sometimes considered unordered).
I am trying to alert a returned value from a function and I get this in the alert:
[object Object]
Here is the JavaScript code:
<script type="text/javascript">
$(function ()
{
var $main = $('#main'),
$1 = $('#1'),
$2 = $('#2');
$2.hide(); // hide div#2 when the page is loaded
$main.click(function ()
{
$1.toggle();
$2.toggle();
});
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible());
});
function whichIsVisible()
{
if (!$1.is(':hidden')) return $1;
if (!$2.is(':hidden')) return $2;
}
});
</script>
whichIsVisible is the function which I am trying to check on.
As others have noted, this is the default serialisation of an object. But why is it [object Object] and not just [object]?
That is because there are different types of objects in Javascript!
Function objects:
stringify(function (){}) -> [object Function]
Array objects:
stringify([]) -> [object Array]
RegExp objects
stringify(/x/) -> [object RegExp]
Date objects
stringify(new Date) -> [object Date]
… several more …
and Object objects!
stringify({}) -> [object Object]
That's because the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.
Usually, when you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.
where stringify should look like this:
function stringify (x) {
console.log(Object.prototype.toString.call(x));
}
The default conversion from an object to string is "[object Object]".
As you are dealing with jQuery objects, you might want to do
alert(whichIsVisible()[0].id);
to print the element's ID.
As mentioned in the comments, you should use the tools included in browsers like Firefox or Chrome to introspect objects by doing console.log(whichIsVisible()) instead of alert.
Sidenote: IDs should not start with digits.
[object Object] is the default toString representation of an object in javascript.
If you want to know the properties of your object, just foreach over it like this:
for(var property in obj) {
alert(property + "=" + obj[property]);
}
In your particular case, you are getting a jQuery object. Try doing this instead:
$('#senddvd').click(function ()
{
alert('hello');
var a=whichIsVisible();
alert(whichIsVisible().attr("id"));
});
This should alert the id of the visible element.
You can see value inside [object Object] like this
Alert.alert( JSON.stringify(userDate) );
Try like this
realm.write(() => {
const userFormData = realm.create('User',{
user_email: value.username,
user_password: value.password,
});
});
const userDate = realm.objects('User').filtered('user_email == $0', value.username.toString(), );
Alert.alert( JSON.stringify(userDate) );
reference
https://off.tokyo/blog/react-native-object-object/
Basics
You may not know it but, in JavaScript, whenever we interact with string, number or boolean primitives we enter a hidden world of object shadows and coercion.
string, number, boolean, null, undefined, and symbol.
In JavaScript there are 7 primitive types: undefined, null, boolean, string, number, bigint and symbol. Everything else is an object. The primitive types boolean, string and number can be wrapped by their object counterparts. These objects are instances of the Boolean, String and Number constructors respectively.
typeof true; //"boolean"
typeof new Boolean(true); //"object"
typeof "this is a string"; //"string"
typeof new String("this is a string"); //"object"
typeof 123; //"number"
typeof new Number(123); //"object"
If primitives have no properties, why does "this is a string".length return a value?
Because JavaScript will readily coerce between primitives and objects. In this case the string value is coerced to a string object in order to access the property length. The string object is only used for a fraction of second after which it is sacrificed to the Gods of garbage collection – but in the spirit of the TV discovery shows, we will trap the elusive creature and preserve it for further analysis…
To demonstrate this further consider the following example in which we are adding a new property to String constructor prototype.
String.prototype.sampleProperty = 5;
var str = "this is a string";
str.sampleProperty; // 5
By this means primitives have access to all the properties (including methods) defined by their respective object constructors.
So we saw that primitive types will appropriately coerce to their respective Object counterpart when required.
Analysis of toString() method
Consider the following code
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
myObj.toString(); // "[object Object]"
myFunc.toString(); // "function(){}"
myString.toString(); // "This is a sample String"
myNumber.toString(); // "4"
myArray.toString(); // "2,3,5"
As discussed above, what's really happening is when we call toString() method on a primitive type, it has to be coerced into its object counterpart before it can invoke the method.
i.e. myNumber.toString() is equivalent to Number.prototype.toString.call(myNumber) and similarly for other primitive types.
But what if instead of primitive type being passed into toString() method of its corresponding Object constructor function counterpart, we force the primitive type to be passed as parameter onto toString() method of Object function constructor (Object.prototype.toString.call(x))?
Closer look at Object.prototype.toString()
As per the documentation,
When the toString method is called, the following steps are taken:
If the this value is undefined, return "[object Undefined]".
If the this value is null, return "[object Null]".
If this value is none of the above, Let O be the result of calling toObject passing the this value as the argument.
Let class be the value of the [[Class]] internal property of O.
Return the String value that is the result of concatenating the three Strings "[object ", class, and "]".
Understand this from the following example
var myObj = {lhs: 3, rhs: 2};
var myFunc = function(){}
var myString = "This is a sample String";
var myNumber = 4;
var myArray = [2, 3, 5];
var myUndefined = undefined;
var myNull = null;
Object.prototype.toString.call(myObj); // "[object Object]"
Object.prototype.toString.call(myFunc); // "[object Function]"
Object.prototype.toString.call(myString); // "[object String]"
Object.prototype.toString.call(myNumber); // "[object Number]"
Object.prototype.toString.call(myArray); // "[object Array]"
Object.prototype.toString.call(myUndefined); // "[object Undefined]"
Object.prototype.toString.call(myNull); // "[object Null]"
References:
https://es5.github.io/x15.2.html#x15.2.4.2
https://es5.github.io/x9.html#x9.9
https://javascriptweblog.wordpress.com/2010/09/27/the-secret-life-of-javascript-primitives/
It's the value returned by that object's toString() function.
I understand what you're trying to do, because I answered your question yesterday about determining which div is visible. :)
The whichIsVisible() function returns an actual jQuery object, because I thought that would be more programmatically useful. If you want to use this function for debugging purposes, you can just do something like this:
function whichIsVisible_v2()
{
if (!$1.is(':hidden')) return '#1';
if (!$2.is(':hidden')) return '#2';
}
That said, you really should be using a proper debugger rather than alert() if you're trying to debug a problem. If you're using Firefox, Firebug is excellent. If you're using IE8, Safari, or Chrome, they have built-in debuggers.
[object Object] is the default string representation of a JavaScript Object. It is what you'll get if you run this code:
alert({}); // [object Object]
You can change the default representation by overriding the toString method like so:
var o = {toString: function(){ return "foo" }};
alert(o); // foo
I think the best way out is by using JSON.stringify() and passing your data as param:
alert(JSON.stringify(whichIsVisible()));
You have a javascript object
$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...
you have to treat $1 and $2 like jQuery objects.
You are trying to return an object. Because there is no good way to represent an object as a string, the object's .toString() value is automatically set as "[object Object]".
Consider the following example:
const foo = {};
foo[Symbol.toStringTag] = "bar";
console.log("" + foo);
Which outputs
[object bar]
Basically, any object in javascript can define a property with the tag Symbol.toStringTag and override the output.
Behind the scenes construction of a new object in javascript prototypes from some object with a "toString" method. The default object provides this method as a property, and that method internally invokes the tag to determine how to coerce the object to a string. If the tag is present, then it's used, if missing you get "Object".
Should you set Symbol.toStringTag? Maybe. But relying on the string always being [object Object] for "true" objects is not the best idea.
The object whose class is Object seems quite different from the usual class instance object, because it acts like an associative array or list: it can be created by simple object literals (a list of keys and properties), like this: let obj={A:'a',B:'b'}; and because it looks very like this same literal notation when displayed in the Developer Tools Console pane and when it is converted to a JSON string.
But, in fact, the only real difference in objects of other classes (which are derived or extended from Object) is that other classes usually have constructors and methods (these are all functions), in addition to properties (which are variables). A class instance object is allocated using the 'new' operator, and its properties and methods are accessible through the 'this' variable. You can also access the underlying static functions that are copied to each new instance by using the 'prototype' property, and even extend system classes by adding new functions to their prototype object.
The Array object is also derived from Object and is frequently used: it is an ordered, 0-indexed array of variable values.
Object objects, unlike Arrays and other classes are treated simply as associative arrays (sometimes considered ordered, and sometimes considered unordered).
I can't figure out how the toString method could possibly be of any use when used on a string. A string is already a string and by its very nature it returns the value of the string.
This...
console.log("Hello"); // => "Hello"
console.log(typeof "Hello"); // => string
Seems exactly the same as this...
console.log("Hello".toString()); // => "Hello"
console.log(typeof "Hello".toString()); // => string
If toString converts something to a string and returns it's value as a string and a string is a string and returns the value of a string I can only conclude that this method is totally meaningless. Am I missing something?
Note: "What is the difference between string literals and String objects in JavaScript?" and "Is there any use value to using the toString method on a string?" are clearly not the same question so I don't think this should be considered a duplicate.
There might be a misunderstanding.
Strings are primitive values, that is, they are not object. And thus they don't have methods.
However, some primitive values can be wrapped in analogous objects. it's the case of booleans, numbers and strings.
When you attempt to use one of these primitive values as an object, e.g. calling a method, the following happens under the hood:
An object wrapper (in this case, a string object) is created
The property is read/written in that object
No reference to that object is stored anywhere, and thus it's usually garbage collected
Therefore, yes, using toString method on a string primitive is usually useless, because it only converts it to an object string under the hood, and the method converts the string object back to a string primitive.
However, that's not the case when you have a string object, because you may want to convert it to a string primitive:
var obj = new String('hello');
typeof obj; // 'object'
var str = obj.toString();
typeof str; // 'string'
A case in which toString used on a string primitive is when you have replaced it with a custom function (not recommended):
String.prototype.toString = function() { return '[' + this + ']' };
'hello'.toString(); // "[hello]"
String object and String literal are two different things. Read more about it here:
What is the difference between string literals and String objects in JavaScript?
I'm not supposed to add elements to an array like this:
var b = [];
b.val_1 = "a";
b.val_2 = "b";
b.val_3 = "c";
I can't use native array methods and why not just an object. I'm just adding properties to the array, not elements. I suppose this makes them parallel to the length property. Though trying to reset length (b.length = "a string") gets Uncaught RangeError: Invalid array length.
In any case, I can still see the properties I've set like this:
console.log(b); //[val_1: "a", val_2: "b", val_3: "c"]
I can access it using the dot syntax:
console.log(b.val_1); //a
If an array is just an object in the same way a string or a number is an object, why can't (not that I'd want to) I attach properties to them with this syntax:
var num = 1;
num.prop_1 = "a string";
console.log(num); //1
I cannot access its properties using dot syntax
console.log(num.prp); //undefined
Why can this be done with array and not with other datatypes. For all cases, I should use {} and would only ever need to use {}, so why have arrays got this ability?
JSBIN
Because arrays are treated as Objects by the language, you can see this by typing the following line of code:
console.log(typeof []) // object
But other types like number literals, string literals NaN ... etc are primitive types and are only wrapped in their object reprsentation in certain contexts defined by the language.
If you want to add properties or methods to a number like that, then you can use the Number constructor like this:
var num = new Number(1);
num.prop_1 = "fdadsf";
console.log(num.prop_1);
Using the Number constructor returns a number object which you can see by typing the following line:
console.log(typeof num); // object
While in the first case:
var num = 1;
console.log(typeof num) // number
EDIT 2: When you invoke a method on a number literal or string literal for instance, then that primitive is wrapped into its object representation automatically by the language for the method call to take place, for example:
var num = 3;
console.log(num.toFixed(3)); // 3.000
Here num is a primitive variable, but when you call the toFixed() metohd on it, it gets wrapped to a Number object so the method call can take place.
EDIT: In the first case, you created a string like this first var str = new String(), but then you changed it to str = "asdf" and then assigned the property str.var_1 = "1234".
Of course, this won't work, because when you assigned str = "asdf", str became a primitive type and the Object instance that was originally created is now gone, and you can't add properties to primitives.
In the second, it didn't output undefined like you said, I tested it in Firebug and everything worked correctly.
EDIT 3:
String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.
This is taken from MDN Documentation, when you use string like that var p = String(3) it becomes a conversion function and not a constructor and it returns a primitive string as you can see from the quote above.
Regarding your second comment, I didn't understand how my comment has been defied, because if you try to console.log(p.pr) you'll get undefined which proves p is a primitive type and not an object.
If an array is just an object in the same way a string or a number is an object,
An array is different than strings, numbers, booleans, null and undefined. An array IS an object, while the others in the list are primitive values. You can add properties to the array just like you would with any other object, anything different being just what makes arrays special (the length property you mentioned for example). You cannot add properties or call methods on primitive values.
In this previous answer i talked about the use of Object wrappers over primitive values. Feel free to read it to see more about Object wrappers. The following will be a very short example:
console.log('TEST'.toLowerCase()) // 'test'
While it may seem that the toLowerCase method is called on the string 'TEST', in fact the string is converted automatically to a String object and the toLowerCase method is called on the String object.
Each time a property of the string, number or boolean is called, a new Object wrapper of the apropriate type is created to get or set that value (setting properties might be optimized away entirely by the browser, i am not sure about that).
As per your example:
var num = 1; // primitive value
num.prop_1 = "a string"; // num is converted to a Number, the prop_1 property is set on the Object which is discarded immediately afterwards
console.log(num); //1 // primitive value
console.log(num.prp); // num is converted to a Number, which doesn't have the prp property
My example:
Number.prototype.myProp = "works!";
String.prototype.myFunc = function() { return 'Test ' + this.valueOf() };
Boolean.prototype.myTest = "Done";
console.log(true.myTest); // 'Done'
console.log('really works!'.myFunc()); // 'Test really works!'
var x = 3;
console.log(x.myProp.myFunc()); // 'Test works!'
console.log(3['myProp']); // 'works!'
On the other hand:
console.log(3.myProp); // SyntaxError: Unexpected token ILLEGAL
The number isn't necessarily treated differently, that syntax just confuses the parser. The following example should work:
console.log(3.0.myProp); // 'works!'
var place = "mundo"["Hola", "Ciao"];
Why does this return undefined? Just because it is garbage?
That is perfectly valid JS, though it doesn't do what you expect.
place is initialized to the 'Ciao' property of String('mundo'). Since it doesn't exist, it is initialized to undefined.
The tricky part:
"Hola","Ciao" is using the comma operator, evaluates "Hola", evaluates "Ciao" and returns "Ciao"
[...] in this case is property access
"mundo"[] "mundo" is converted to a String object to access the property on it.
Proof:
var place = "mundo"["Hola", "toString"];
console.log(place) // function toString() { [native code] }
The array operator on a string object will either try to index into the string and return a specific character from that string (on some JS implementations) or it will try to lookup a property on that object. If the index is a number, some JS implementations (I think this is non-standard behavior) will give you that character from the string.
// returns "m" in Chrome
"mundo"[0]
// returns undefined
"mundo"[9]
But, an array index that isn't a number will try to look for that property on the string object and your particular value won't be found on the string object and thus you get undefined.
// does a property lookup and returns "function toString{[native code]}
"mundo"["toString"]
// returns undefined - no propery named foo
"mundo"["foo"]
So, since there is no property on the string that resembles anything in ["Hola", "Ciao"], you get undefined. Technically, the browser is actually looking for the "Ciao" property when you give it this and because that property doesn't exist, you get undefined.
In a weird test, you can run this code to sort of see what's going on:
var str = new String("mundo");
str["Ciao"] = "Hello";
alert(str["Hola", "Ciao"]); // alerts "Hello"
Working demo of this: http://jsfiddle.net/jfriend00/e6R8a/
This all makes me wonder what in the heck you are actually trying to do that comes up with this odd construct.