Background: I’m an old IT puke (80+) who wrote his first code before '65; long since retired. I’m amusing myself these days learning new topics (HTML, CSS, javascript) and developing private web pages.
I’m taking a javascript tutorial which has caused me to create a file of javascript wrapped up in some HTML. I’m using VS Code, but I have almost no knowledge of or experience with it. I’ve used code editors in the past, but VS Code is a different animal - very powerful and flexible . . . so much so that I can’t find a place to grab hold and chew on it. I’ve tried to keep my use of VSC as default as possible with no add ons, but I’m thinking it’s time to put a toe in the water.
My tutorial’s HTML file is not working properly. The HTML is ok; the problem is with the javascript code. I think I have a syntax problem, but I can’t seem to find it. I’ve looked at it until I can’t ‘see’ it. When I open it with File Server, it displays the content ok but I see an error in the Console (per screenshot)
I think the error is syntax because the VS Code window shows a left curly bracket ({) in red at line 22 indicating a missing pair, but I cannot find it.
Am I correct that the error is syntax? If so, do you have any suggestions for how to find the problem? If not syntax, what is the problem?
I did a bit of searching before coming here. I was looking for information about syntax checking for js in VSC. I found a plug-in called ESLint. I think I installed it, but have no clue if I did, and if I did, how to invoke it and, if I were to invoke it, how to use it to check js syntax.
Without seeing the full code, my best guess is that you are missing the closing curly brace (}) for your function definition. It could be missing entirely, or you could have gotten your nested tokens out of order. Typically, if you click a brace, parenthesis, etc in VSC it will highlight the corresponding opening/closing token.
Generally, VSC’s syntax awareness is going to work better if you have your JavaScript in a .js file and your HTML in a .html file.
There are also a few extensions which will color-code matching token pairs, as well as linter extensions that can provide some more helpful error indications.
For example:
As said, the fact that the opening { is in red suggests it isn’t closed correctly.
Also, just as an aside, your script element can not come before the HTML it is accessing.
<body>
<script>
const h1 = document.querySelector("h1");
console.log(h1); // null because the script is executed before the h1 is rendered
</script>
<h1>hello world</h1>
</body>