JavaScript Internal and External concept

Java script internal and external  concept:-

You can use JavaScript code in two ways.

  1. You can either include the JavaScript code internally within your HTML document itself
  2. You can keep the JavaScript code in a separate external file and then point to that file from your HTML document.

What is Internal JavaScript?

We have been using Internal JS so far. Here is a sample –

Example:-

<html>
<head>
<title>My First JavaScript code!!!</title>
<script type=”text/javascript”>
// Create a Date Object
var day = new Date();
// Use getDay function to obtain todays Day.
// getDay() method returns the day of the week as a number like 0 for Sunday, 1 for Monday,….., 5
// This value is stored in today variable
var today = day.getDay();
// To get the name of the day as Sunday, Monday or Saturday, we have created an array named weekday and stored the values
var weekday = new Array(7);
weekday[0]=”Sunday”;
weekday[1]=”Monday”;
weekday[2]=”Tuesday”;
weekday[3]=”Wednesday”;
weekday[4]=”Thursday”;
weekday[5]=”Friday”;
weekday[6]=”Saturday”;
// weekday[today] will return the day of the week as we want
document.write(“Today is ” + weekday[today] + “.”);
</script>
</head>
<body>
</body>
</html>

Output:-

Today is Tuesday.

What is External JavaScript?

You plan to display the current date and time in all your web pages. Suppose you wrote the code and copied into all your web pages (say 100). But later, you want to change the format in which the date or time is displayed. In this case, you will have to make changes in all the 100 web pages. This will be a very time consuming and difficult task. So, save the JavaScript code in a new file with the extension .js. Then, add a line of code in all your web pages to point to your .js file like this:
<script type=”text/javascript” src=”currentdetails.js”>
Note: : It is assumed that the .js file and all your web pages are in the same folder. If the external.js file is in a different folder, you need to specify the full path to your file in the src attribute.

This is your currentdetails.js file. Don’t worry seeing long lines of code. You will learn to code soon. Make changes to your HTML document like this:
<html>
<head>
<title>My External JavaScript Code!!!</title>
<script type=”text/javascript” src=”currentdetails.js”>
</script>
</head>
<body>
</body>
</html>

When to Use Internal and External JavaScript Code?

If you have only a few lines of code that is specific to a particular webpage, then it is better to keep your JavaScript code internally within your HTML document.

On the other hand, if your JavaScript code is used in many web pages, then you should consider keeping your code in a separate file. In that case, if you wish to make some changes to your code, you just have to change only one file which makes code maintenance easy. If your code is too long, then also it is better to keep it in a separate file. This helps in easy debugging.