Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

why this syntax not producing Error {age:15}toString() in javascript

Try this syntax in console

 {age:15}toString()  
 '[object Undefined]' // this is the return

why this happens it looks syntactically wrong so I’m not sure how the interpreter parse it ?

the object {age:15} looks like completely ignored ? is that true ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

if not ignored dose it mean it garbage as soon as it created I’m just thinking but not sure

>Solution :

{age:15}:

  1. Is a block. It is not an object. For more information see What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012? and in particular the explanations for {} + [] and {} + {} that deal with the same block behaviour.
  2. It contains a label with identifier age which is then followed by the expression-statement 15. For more see What does the JavaScript syntax foo: mean?
  3. It is irrelevant to the rest of the code.

The actual output here is only from toString():

console.log(toString());

With that in mind let’s examine the output: toString() is a method on the object prototype. Thus pretty much all objects have it. Including window:

console.log("toString" in window); //true

Calling just toString() means the method will be picked up from the global object – window.

Because the value of this is determined at call time and implicitly there is no object to pick it from:

A normal call would look like someObject.toString() which will set the this value to someObject. It is also equivalent to calling Object.prototype.toString.call(someObject) which will explicitly set the value of this to `someObject.

However with the entire toString() is basically equivalent to Object.prototype.toString.call(undefined) as there is nothing the method is called on.

console.log(Object.prototype.toString.call(undefined))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading