Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript window.document in the console [duplicate]

In Chrome the console object defines two methods that seem to do the same thing:

console.log(...)
console.dir(...)

I read somewhere online that dir takes a copy of the object before logging it, whereas log just passes the reference to the console, meaning that by the time you go to inspect the object you logged, it may have changed. However some preliminary testing suggests that there's no difference and that they both suffer from potentially showing objects in different states than when they were logged.

Try this in the Chrome console (Ctrl+Shift+J) to see what I mean:

> o = { foo: 1 }
> console.log(o)
> o.foo = 2

Now, expand the [Object] beneath the log statement and notice that it shows foo with a value of 2. The same is true if you repeat the experiment using dir instead of log.

My question is, why do these two seemingly identical functions exist on console?

like image 669
Drew Noakes Avatar asked Nov 18 '22 03:11

Drew Noakes


2 Answers

In Firefox, these function behave quite differently: log only prints out a toString representation, whereas dir prints out a navigable tree.

In Chrome, log already prints out a tree -- most of the time. However, Chrome's log still stringifies certain classes of objects, even if they have properties. Perhaps the clearest example of a difference is a regular expression:

> console.log(/foo/);
/foo/

> console.dir(/foo/);
* /foo/
    global: false
    ignoreCase: false
    lastIndex: 0
    ...

You can also see a clear difference with arrays (e.g., console.dir([1,2,3])) which are logged differently from normal objects:

> console.log([1,2,3])
[1, 2, 3]

> console.dir([1,2,3])
* Array[3]
    0: 1
    1: 2
    2: 3
    length: 3
    * __proto__: Array[0]
        concat: function concat() { [native code] }
        constructor: function Array() { [native code] }
        entries: function entries() { [native code] }
        ...

DOM objects also exhibit differing behavior, as noted on another answer.

like image 64
apsillers Avatar answered Feb 01 '23 22:02

apsillers


Another useful difference in Chrome exists when sending DOM elements to the console.

Notice:

  • console.log prints the element in an HTML-like tree
  • console.dir prints the element in a JSON-like tree

Specifically, console.log gives special treatment to DOM elements, whereas console.dir does not. This is often useful when trying to see the full representation of the DOM JS object.

There's more information in the Chrome Console API reference about this and other functions.

like image 21
Drew Noakes Avatar answered Feb 01 '23 22:02

Drew Noakes