Why do I get an error instead of logging "undefined" to the console when using console.log() on a variable I create later but within another script tag?
P粉579008412
P粉579008412 2023-09-12 22:58:00
0
1
544

Why does this code snippet give the error "Uncaught ReferenceError: x is not Defined" in the console

<body>
    <script>
        console.log(x);
    </script>
    
    <script>
        var x = 10;
    </script>
</body>

And this record is "Undefined"?

<body>
    <script>
        console.log(x);
        var x = 10;
    </script>
</body>

I'm trying to understand variable declaration and variable scope. And expect boosting to happen since the entire code is in the same page. But because the console.log() is separated in another script tag, I get an error instead of just logging "undefined" in the console.

P粉579008412
P粉579008412

reply all(1)
P粉536909186

var is promoted, which means it can be accessed at the beginning of the scope in which it is defined, even though the declaration line may be at the end of the scope. If you access the var before declaring it, it is undefined because you still need to perform the declaration and possibly initialize the variable to a specific value. So that's how your second example works.

Read about boosting here:

https://developer.mozilla.org/en-US/docs/glossary/lifting

But in the first example 2 has 2 different scopes, so the var basically doesn't exist in the first script, hence the error not Defined .

Learn about var and its scope here:

https://developer.mozilla.org /en-US/docs/Web/JavaScript/Reference/Statements/var

important I strongly advise against using var. Please use const and let instead. Using var for promotion can lead to errors that are sometimes difficult to debug and fix. If you need to use only var in production, just use esbuild to downgrade your code to the appropriate older version of JS.

Interestingly, const and let are also somewhatelevated, but accessing them in an elevated state causes a runtime error (this is called a transient dead zone), which is why they are safer because you get the error immediately, rather than silently raising var, leaving you with a potential error that you don't know about.

About the temporal dead zone:

https://developer.mozilla .org/en-US/docs/Web/JavaScript/Reference/Statements/let#temporal_dead_zone_tdz

<body>
    <script>
        console.log(x);
        const x = 10;
    </script>
</body>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!