So why should you read this tutorial, instead of the many others out there? Here are a couple of reasons:
- It’s concise: no dreaded explanations
- For beginners: I assume you have little knowledge of programming and the ecosystem
- I include lot’s of example code
- Excercises: you won’t learn programming languages by just reading, hence I included many exercises
- Check user input, even before sending it to a backend server
- React to user events, like clicking an element and hovering the mouse somewhere
- Fetch data from a backend interactively, without having to reload the page
- Show or hide parts of a website, based on certain conditions
- Embedding it directly in the page, between the script tags.
Let’s create that Hello world example right away, to demonstrate option 1:
<script> alert('Hello, world!'); </script>
The alert function shows a simple dialog box or popup in your browser, with the provided text and an OK button to close it. Feel free to run and modify the example above.
hello-world.js, you put just the code, without any tags:
Doing both at once
<script src="code-file-1.js"></script> <script src="code-file-2.js"></script> <script> alert('Hello world!'); </script>
Please note that the examples that reference external files don’t work here, since the files don’t exist on my server.
<script> alert(12 - '5'); </script>
If you run this, the popup will show you the result, which is the number 7.
There are not many situations where this is desirable. E.g., you could use it to directly do calculations from user input, but I would still want to check the user input first, just to be sure they didn’t enter something else than digits, causing a NaN (not a number) result.