JavaScript - Hello World
JavaScript - Hello World Program
Write βHello Worldβ Program in JavaScript
βHello, World!β is often the first program, programmers write when learning a new programming language. JavaScript βHello Worldβ is a simple program, generally used to demonstrate the basic syntax of the language. This program will make use of different JavaScript methods to print βHello Worldβ.
Using document.write()
In JavaScript, the simplest way to print βHello Worldβ is to usedocument.write()method. The document.write() method writes the content (a string of text) directly to the HTML document or web page. Lets look at the following β
<script>
document.write("Hello World)
</script>We should write the document.write() within the <script> and </script> tags. We can place the <script> inside the <head> or <body> section.
Example
Letβs try to write a JavaScript program that prints the βHello World!β to the document or web page. In the below program, we placed the JavaScript code within the <head> section. You can try to put the JavaScript part inside the <body> section and execute the program.
Using alert() method
We can use the windowalert()method to print βHello Wordβ in a dialogue box.
The alert() is a window method that instruct the browser to display an alert box with the message. We can write alert without passing any message to it.
<script>
alert("Hello World")
</script>We can write alert() method as window.alert(). As window object is a global scope object, we can skip the βwindowβ keyword.
Example
Letβs try an example showing βHello Worldβ in the alert box. Try to execute the program by putting the <script> part within the <body> section.
Using console.log()
Theconsole.log()is a very convenient method to print the message to web Console. It is very useful to debug the JavaScript codes in the browsers. Letβs look at the simple application of the console.log() to print the βHello Worldβ to theweb console.
<script>
Console.log("Hello World")
</script>We can use the console.log to print strings or JavaScript objects. Here in above code snippet, we have passed βHello Worldβ as a string argument to the console.log() method.
Example
Letβs try to write a complete JavaScript program with HTML.
It will produce the following message in the web console β
Hello WorldUsing innerHTML
TheinnerHTMLproperty of an HTML element defines the HTML content of the element. We can use this property to display the Hello World message. By changing theinnerHTMLproperty of the element, we can display the message in HTML document or webpage.
To use innerHTML property of an element, we need to access that element first. We can use document.getElementById() method to access the element. Letβs look at a complete example.
Example
In the example below, we define a div element with id, βoutputβ. We access this element using the document.getElementById(βoutputβ). Then we change the innerHTML property and display our message, βHello Worldβ.