20 Feb JavaScript – Run First Script
In this lesson, we will create and run our first script in JavaScript. We can display the data or you can say print something in JavaScript using:
- document.write(): Used mostly for testing
- innerHTML: Preferred in Real World
- console.log(): For Debugging
document.write() in JavaScript
The document.write() is a method in JavaScript to print. It is mostly used for testing and not a preferred way. Using it on a web page loads the page slowly and is not considered a good approach.
Let us see an example to print in JavaScript using document.write():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p>We are printing a number:</p> <script> document.write(25); </script> </body> </html> |
Output
innerHTML in JavaScript
The innerHTML is a property to define the content in HTML. You can write into an HTML element using innerHTML. With that, the id attribute is also used to define that specific HTML element. This id is set in the following:
1 2 3 |
document.getElementById(id) |
Let us see an example to implement the innerHTML in JavaScript:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p>We are printing a number:</p> <p id="test"></p> <script> document.getElementById("test").innerHTML = 25; </script> </body> </html> |
Output
NOTE: In this complete tutorial, we will use the best approach i.e., innerHTML, since it loads the web page faster than using document.write().
console.log() in JavaScript
The console.log() method is used in JavaScript to display the data in the console. It is mainly used for debugging purposes.
Let us see an example to print using the console.log():
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<!DOCTYPE html> <html> <body> <h2>Demo Heading</h2> <p>Press F12 on your keyboard and select Console.</p> <p>We are printing a number:</p> <script> console.log(25); </script> </body> </html> |
Output
To view the output on the console, press F12 on the web browser. Then, click the Console tab as shown below:
No Comments