Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{} + [] - why it is 0 or [object Object]?

Tags:

javascript

If you open a JS Console in your browser (in my case Chrome) and type:

{} + []

you will get 0, but when you type

console.log({} + [])

you get [object Object]... any ideas why the result is different? I've always thought that when you type there it always wrap it with console.log?

like image 513
kuba Avatar asked Oct 11 '17 08:10

kuba


People also ask

What is {} and [] in JavaScript?

{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array . [] is shorthand for creating an empty array.

How do you know if an object is zero?

Test("new int[0]", new int[0]); // false // Note: object[] o = new int[0]; wouldn't be allowed. } } } This includes some test cases that could be an indication that the check you're attempting to do isn't a good idea, but it also indicates that it gives accurate results. Show activity on this post.

Why do I keep getting object object in JavaScript?

From the image above, instead of having the object and its properties displayed, [object, object] was displayed. This happens because when you use the alert() method to display an object in JavaScript, you get the string format displayed. To fix this, you can use the JSON.

What is meant by object object?

[object Object] is a string version of an object instance. This value is returned by a JavaScript program if you try to print out an object without first formatting the object as a string.


1 Answers

{} can either be an empty block or a empty object literal depending on context.

+ can either be the unary plus operator or the concatination operator depending on context.

The first code example is an empty block it might as well not be there, making the expression the same as +[], meaning "An empty array converted to a number".

You can't have a block as a function argument, so the second code example {} is an object and the code means "Concatinate an object with an array" (implicitly converting both object and array to strings).

like image 194
Quentin Avatar answered Sep 22 '22 17:09

Quentin