0

I'm following a JS course on Udemy, the teacher shows that snippet of code while explaining document:

<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <div id="start">Start</div>

    <ul>

        <li>Element 1</li>
        <li>Element 2</li>

    </ul>

    <button onclick="one()">Click!</button>

    <button onclick="two()">Replace!</button>

    <script>
        function one() {

            **x** = document.createElement("p");
            x.innerHTML = 'Start Four';
            document.getElementById('start').appendChild(x);

        }

        function two() {

            y = document.createElement('p');
            y.innerHTML = 'Start Five';
            document.getElementById('start').replaceChild(y, **x**);

        }
    </script>

</html>

From what i have understood the variable x in function one() should have a function block scope, i can't actually get why the browser doesn't give any error when x is passed as an argument in function two().

I expected the browser to throw an error

InSync
  • 4,851
  • 4
  • 8
  • 30
zheyon
  • 3
  • 1
  • 1
    It will only become scoped to the function if you declare it with the `var` keyword, or scoped to the block if you declare it with `let` or `const`. If you don't use any of those keywords, it will just become a property of the `window` object and thus accessible from anywhere. – Lennholm Jul 30 '23 at 22:17

1 Answers1

1

Since x is not explicitly declared with var, let, or const, it becomes a global variable (a property of the global object, which in the browser is the window object). Hence, it is accessible in the entire global scope (outside the function). note: I am still learning so i might be wrong :D GL

Mito
  • 34
  • 3