Here is a basic “Hello World!” exercise in JavaScript. Online code editors like JSFiddle and Codepen truly come into their own when learning JavaScript. This simple example uses JavaScript’s alert
method to display a “pop-up” type message when the page loads (this is not a good thing to do on your website, by the way, it is considered intrusive).
In this tutorial:
Required knowledge:
1. jsFiddle
2. Codepen
See the Pen Hello World! by David Fox (@foxbeefly) on CodePen.
3. HTML Web page
Or copy-paste the below code into an HTML file and fire up your browser!
<html> <head> <title>Hello World! JavaScript</title> </head> <body> <h1>Hello World! JavaScript</h1> <script> alert("Hello World!"); </script> </body> </html>
JavaScript code is included in your HTML files between the <script>
tags. The <script>
tags are in turn nested in the <head>
or <body>
tags.
The HTML file is sent by the web server to the client’s device where it is executed by the browser.
4. methods & functions
This is a bit advanced — for now, just bear the following terms in mind:
A function is a reusable block of code that does something and can be called from somewhere. A method is a function that belongs to an object. The alert()
function is a method of the Window
object. JavaScript has many, many “built-in” objects with methods for you to use, and of course, later you will write your own. [1]
5. Next steps
- Variables & constants in JavaScript
- Code a JavaScript function
References:
- MozDevNet (no date) Functions – reusable blocks of code – Learn web development: MDN, MDN Web Docs. Available at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Functions (Accessed: 8 January 2024).
- MozDevNet (no date) Function return values – Learn web development: MDN, MDN Web Docs. Available at: https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Return_values (Accessed: 8 January 2024).