Hello World in JavaScript
Video Tutorial
Overview
JavaScript is one of the most popular and primary languages in the web development community. There are multiple ways to print "Hello World" in JavaScript, and for that, we first must know how to insert JavaScript code in an HTML file using the <script> tag. We can also control the loading and execution behavior of a script using the async and defer attributes provided by HTML5.
Scope
- This article discusses three different ways to print hello world in JavaScript.
- We also discuss how to insert JavaScript code into an HTML file.
- Lastly, the new async and defer attributes in HTML5 are explained.
Introduction to Hello World in JavaScript
If you ask programmers what was their first program? Most of them would say the "Hello, World" program.
It is a simple program that prints a Hello, World! message on the screen, and it’s a good way to make sure your development environment is properly configured.
In this article, you will begin your journey into programming by exploring different ways to write the hello world in JavaScript.
Prerequisite
You need a basic understanding of HTML.
What is JavaScript?
JavaScript is a high-level interpreted programming language initially created to make web pages interactive.
- High level means that it is easy to understand.
- Interpreted means that a JavaScript executes line-by-line.
The programs in JavaScript are called scripts. Today, JavaScript is used in multiple domains like:
- Adding interactivity to web pages (Front-end Development).
- Programming servers (Back-end development)
- Mobile App Development
- Desktop App Development and many more...
Where to write code?
You can write JavaScript code in any text editor. I recommend using the free VS Code Editor for its extensions and vast community support. If you prefer, you can use online code editors like ide.new or vscode.dev.
So, Let's begin.
Takeaways:
- Hello World is a program to display "Hello, World" on the screen.
- JavaScript is a programming language used to make web pages interactive.
How to Insert JavaScript into an HTML Page
Before we see different ways to print "Hello World" in JavaScript, we must know how to add JavaScript code to an HTML page.
There are two ways you can insert a JavaScript program into an HTML document.
- Internal JavaScript
- External JavaScript
Both methods make use of the <script> tag to do this. Let's go over both methods.
Internal JavaScript
When using internal JavaScript, we directly put the code inside of the <script> tag. When the browser encounters this tag, it automatically executes the code.
Let's see an example:
We can put the <script> tag anywhere in our HTML. Mostly it is added either at the end of the <body> tag or inside the <head> tag. Both have its consequence that we will discuss later.
The // is used to put comments inside the code, its only purpose is to explain the code to a human, and the comment is ignored by the browser.
External JavaScript
When the lines of JavaScript code increase, it becomes difficult to maintain all the code inside HTML. That's why we use an external dedicated JavaScript file. This file is then linked to the HTML using the <script> tag.
JavaScript file ends in a .js extension.
Here is how you use the <script> tag to link a JavaScript file:
The src attribute contains the path to the JavaScript file.
- /path/to/script.js is an absolute path to the script from the root folder.
- An absolute path refers to the complete details needed to locate a file or folder, starting from the root element and ending with the other subdirectories. It is the full path of a file or folder.
- We can also provide a relative path, For example, if the directory structure is as follows:
. ├── index.html └── script.js
that is, if both the script.js andindex.html are in the same folder, then we can just write src="./script.js" in the index.html file.- Relative Path is the hierarchical path that locates a file or folder on a file system starting from the current directory.
- You can even provide a URL in the src attribute to insert a remote JavaScript file, for example:
Again, you can put an external script tag anywhere.
Note 📝
- Only put simple scripts in HTML.
- Using separate files allows the browser to cache it (store in memory for future use). This makes the pages load faster.
- If the src attribute of the <script> tag is set, then the code inside <script> (if any) is ignored.
Takeaway:
- We can add JavaScript to a web page using the <script> tag either by inserting it into HTML (internal JS) or linking an external file (external JS).
3 Ways of Printing Hello World in JavaScript with Examples
Now, let's see 3 methods for printing Hello World in JavaScript.
In all the 3 examples, we will use internal JavaScript as the code is very short and simple.
Using console.log()
The console.log() is a function used to log messages on the web console.
A function in programming is like a black box that takes an input and returns an output by doing some processing.
Let's use console.log to print Hello, World!:
In our case, the console.log takes the text we want to display as input and prints it on the screen as the output.
Output: To see the output, open the HTML file with this script in your browser and press F12 or right-click and select inspect then switch to the second tab named console.
You will find the following output:
console.log() is often used in debugging the code (finding and fixing the errors).
Using document.write()
document.write() is another function you can use to print Hello World in JavaScript. Unlike console.log it prints the message on the HTML document instead of the console.
Let's try it as follow:
To see the output, open the HTML document in your browser:
There is a better alternative to display text on an HTML document using DOM manipulation which is not difficult but beyond the scope of this article.
Using alert()
The last function we will use to print Hello World in JavaScript is alert.
This function displays a pop-up box over the current window with the specified message.
Takeaway:
- You can print Hello World in JavaScript using console.log(), document.write(), alert() functions.
Modern Markup
The <script> tag has a few attributes that are rarely used nowadays but can still be found in old code:
The Type Attribute: <script type=...>
The old version of HTML - HTML4 required this attribute. It's no longer required, although modern HTML - HTML5 uses it to define a script as a module.
The Language Attribute (Deprecated): <script language=…>
This attribute was used to define the language of the script. It is no longer required as JavaScript is the default language.
Takeaway:
- The type and language attribute of the <script> tag are no longer required in HTML5.
The Async and Defer Attributes
Earlier in the article, we stated that we can place the <script> tag anywhere in the HTML code but where we do it has its consequence.
We will first discuss what happens when we put the script tag in the head and at the end of the body tag and then learn about two newly added attributes in HTML5 to alter the behavior of script loading and execution.
Placing script in the head tag
Consider the following example:
The HTML is parsed until the <script> tag is encountered. At that point, parsing of the HTML is blocked and a request is made to fetch (download) the script file. Once the script is executed, HTML parsing resumes again.
This means that placing the <script> tag in the head tag may delay the rendering of the HTML especially if the script has many lines of code. In our case, we will see <h1>Hello, World</h1> after the script.js is downloaded and executed.
Here is a diagrammatic representation of this case:
One more issue possible with placing the script in the head tag is that in some cases if you are trying to operate on items that are on the page, you will get errors, and/or your code will not appear to work because the script has executed before the rest of the page has finished loading.
Placing script at the end of the body tag
Because of the issues of the previous method, placing scripts at the end of the body tag is preferred:
Now, the parsing is done without any pauses, and when it is finished, the script is fetched and executed. This makes the page appear faster to the user.
Here is the diagrammatic representation for this method:
Using async and defer
async and defer are <script> tag attributes that can be used to increase website loading times.
With async, the file gets downloaded asynchronously and then executed as soon as it’s downloaded. Example:
With defer, the file gets downloaded asynchronously but executed only when the document parsing is completed. Example:
<script defer src="script.js"></script>
Loading a script simultaneously with the web page is called asynchronous loading.
Let's look at the diagrammatic representation of both:.
Async Loading
Defer Loading
Async vs Defer
Async | Defer |
---|---|
async blocks the parsing of the page. | defer does not blocks the parsing of the page |
Scripts with async are executed when they become available. | Scripts with defer are executed in the order they appear in HTML. |
In terms of page rendering, defer is better than async. Defer is similar to putting the script at the end of the body tag, except that the script is downloaded in parallel with HTML parsing. | async may cause a delay in page rendering. |
Supported Browsers
Most modern browsers like Chrome, Safari, Edge, and Firefox support the async and defer attributes.
Takeaway:
- You can use async and defer to control the loading and executing behavior of a script. This can help improve page performance.
Conclusion
- Hello World in JavaScript is a program to display the “Hello, World” message on the screen.
- JavaScript is a programming language used to make web pages interactive.
- You can add JavaScript to a web page using the <script> tag in two ways:
- Internal JavaScript: Directly writing the code inside the <script> tag.
- External JavaScript: Linking an external file using the src attribute of the <script> tag.
- You can print hello world using one of the following functions in JavaScript:
- console.log()
- document.write()
- alert()
- HTML5 doesn't require the type and language attribute of <script> tag.
- You can use async and defer to control the loading and executing behavior of a script. This can help improve page performance.