Uncaught Reference Error

app.js

"use strict";var tb = {    rahmen: {        eigenschaften: [            "hochwertig",            "verwindungssteif",            "vergleichsweise verwindungssteif",            "sehr verwindungssteif",            "sehr hohe Verwindungssteifigkeit",            "hohe Steifigkeit"        ]    }};

index.html

<!DOCTYPE html><html lang="en"><head>  ((Some Head-Tags))  <script src="dist/app.js" defer></script>  ((Some Head-Tags))</head><body>  <div class="container">    <section>      <h1>Test</h1>      <script>        console.log(tb.rahmen.eigenschaften[3]);      </script>    </section>  </div></body></html>

Error Message Uncaught ReferenceError: tb is not defined

The problem It must be something simple, but after reading many posts I still have no clue. Why is my Javascript-Object still undefined.


The reason for the error is that you have defer on your script tag for app.js, so that code isn’t run until after all the HTML has been parsed. But your inline script trying to use tb isn’t deferred, so it will run as soon as it’s encountered, which is during the HTML parsing and thus before app.js is run.

The spec has a great graphic showing what defer and such do:

enter image description here

I’d suggest keeping all of the logic in app.js and removing the second script. If you need to add content there with your script, do it via the DOM after the HTML has been parsed.

For instance, if you wanted to add content there:

app.js:

"use strict";var tb = {    rahmen: {        eigenschaften: [            "hochwertig",            "verwindungssteif",            "vergleichsweise verwindungssteif",            "sehr verwindungssteif",            "sehr hohe Verwindungssteifigkeit",            "hohe Steifigkeit"        ]    }};document.getElementById("main-section-content").textContent = tb.rahmen.eigenschaften[3];

index.html:

<!DOCTYPE html><html lang="en"><head>  ((Some Head-Tags))  <script src="dist/app.js" defer></script>  ((Some Head-Tags))</head><body>  <div class="container">    <section>      <h1>Test</h1>      <div id="main-section-content"></div>    </section>  </div></body></html>

Notice that now there’s just one script, which does its work when loaded.