Search code examples
javascriptscopehoisting

javascript variable scope related hoistring


this is my problem.

<html>
<head>
</head>
<body>
    <script>
        var name;
        console.log(name);
        name = "abcdefg";
        console.log(name);
    </script>
</body>
</html>

this code's output is

enter image description here

i know that first log have to said undefined because Hoisting.

i already tried refresh and delete cache and don't understand why. please help me.


Solution

  • name is a reserved variable name of the window. So when you first access the name without overriding it (var name does not override), you get the global property window.name.

    In your case at the first console.log you may get something differ undefined, but not equal to the abcdefg

    <html>
    <head>
    </head>
    <body>
        <script>
            var name;
            console.log(name);
            name = "abcdefg";
            console.log(name);
            console.log(window.name);
        </script>
    </body>
    </html>