0

I cannot understand a behavior of this JS code. The d object in this loop becomes somehow nested in a browser console. Run the code snippet below in a browser or see it in http://jsfiddle.net/qhsjyzob/ and check the second and third console.log in the browser console. Why does it show that the d object is like this:

{
    Hello: {
        World: {}
    }
}

when it has to be like this only:

{
    Hello: {}
}

Here is the code or in http://jsfiddle.net/qhsjyzob/:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title></title>
</head>

<body>
    <script type="text/javascript">
        'use strict';

        var e = ['Hello', 'World'];
        var d = {}

        for (var g = 0; g < e.length; g++) {

               console.log("1: ", d, g, d[e[g]], e[g]);

            d[e[g]] = d[e[g]] || {};

               console.log("2: ", d, g, d[e[g]], e[g]);

               console.log("3: ", d, g, d[e[g]], e[g]);

            d = d[e[g]]

               console.log("4: ", d, g, d[e[g]], e[g]);
        }
    </script>
</body>

</html>
Green
  • 28,742
  • 61
  • 158
  • 247
  • 2
    I'm confused. What you are trying to achieve here ? – Suresh Atta Sep 13 '15 at 12:56
  • The answer to your question lies in the statement `d = d[e[g]];`. What did you intend for that statement to do? – Pointy Sep 13 '15 at 12:57
  • I'm not trying to achieve anything. I just don't understand why browser console in the very first iteration shows that `d` is nested. How does it happen? When I run the code in Node.js, the output is as I expect - `d` is not nested. – Green Sep 13 '15 at 13:00
  • The browser console can play tricks on you because it's not synchronous. Sometimes it's better to log objects with `console.log(JSON.stringify(d))` for example. – Pointy Sep 13 '15 at 13:01
  • @Pointy, no, `d[e[g]]` is an empty object. So `d = d[e[g]]` makes `d` to be equal an empty object, but not a nested `{ world: {} }` – Green Sep 13 '15 at 13:05
  • @Pointy, yes, with `console.log(JSON.stringify(d))` it works as I expect. Strange. Thank you. – Green Sep 13 '15 at 13:06

0 Answers0