JavaScript Example

JavaScript is a simple language that is widely used for adding interactivity to web pages. You can write JavaScript code in three different places: within the <body> tag, within the <head> tag, or in an external JavaScript file. This flexibility makes JavaScript a powerful tool for dynamic web development.

JavaScript Example 1: Basic Code within the Body Tag

This example shows how to write JavaScript within the <body> tag and display dynamic content using the document.write() method.

Example


<script type="text/javascript">
document.write("JavaScript is a simple language for Javatpoint learners");
</script>

Output

JavaScript is a simple language for Javatpoint learners

JavaScript Example 2: Simple Alert between the Body Tag

In this example, we use the alert() function to display a message in a dialog box when the page is loaded.

Example


<script type="text/javascript">
alert("Hello Shorat");
</script>

Output

An alert box will appear with the message: "Hello Shorat"

JavaScript Example 3: Code between the Head Tag

This example demonstrates placing JavaScript code inside the <head> tag and creating a function to display an alert on an onclick event.

Example


<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function msg() {
    alert("Hello Shorat");
}
</script>
</head>
<body>
<p>Welcome to JavaScript</p>
<form>
<input type="button" value="Click" onclick="msg()"/>
</form>
</body>
</html>

Output

Welcome to JavaScript

3 Places to Put JavaScript Code