If your wondering that where to put your java code?

here,is the solution

JavaScript provides 3 places to put the JavaScript code:

  1. In .js file (external JavaScript)
  2. Between the body tag of html
  3. In .js file (external JavaScript)

1) Code between the body tag

In the previous example, we have displayed the dynamic content using JavaScript. Let’s see the simple example of JavaScript that displays alert dialog box.

<script type=“text/javascript”>  

 alert(“Hello Letuslearn”);  

</script>  

here alert function is used to display the alert dialog box

2) Code between the head tag

Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside the head tag.

In this example, we are creating a function msg(). To create function in JavaScript, you need to write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call msg() function.

<html>  

<head>  

<script type=“text/javascript”>  

function msg()

{  

 alert(“Hello Letuslearn”);  

}  

</script>  

</head>  

<body>  

<p>Welcome to Letuslearn JavaScript Tutorial</p>  

<form>  

<input type=“button” value=“click” onclick=“msg()”/>  

</form>  

</body>  

</html>  

3) External JavaScript file

We can create external JavaScript file and embed it in many html page.

It provides code re-usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed all JavaScript files into a single file. It increases the speed of the Webpage. However there is some controversy also that putting all the JavaScript in a single file doesn’t affect the speed.


Let’s create an external JavaScript file that prints Hello Letuslearn in a alert dialog box.

message.js

function msg(){  

 alert(“Hello Javatpoint”);  

}  

Let’s include the JavaScript file into html page. It calls the JavaScript function on button click.

index.html

<html>  

<head>  

<script type=“text/javascript” src=“message.js”></script>  

</head>  

<body>  

<p>Welcome to JavaScript</p>  

<form>  

<input type=“button” value=“click” onclick=“msg()”/>  

</form>  

</body>  

</html>  

NOTE:Make sure to save both the files in the same directory/folder,However you can also save .js files in another folder but to use them you have to specify the path also with the name of function used

Comments in Java Script