Writing a JavaScript

Writing a JavaScript is very simple, you do not need a special program to create a JavaScript, what you need is a simple text editor like Notepad. However, a better editor is Notepad++, which is available online for free. Click to download  https://notepad-plus-plus.org/download/v6.9.html.

You can either embed a JavaScript in a HTML document or you can create a JavaScript file and then reference it in a HTML document using the keyword SRC.

For example, you can embed the text “Welcome to my tutorial” in the following HTML document

<!DOCTYPE html>

<html>
<head>
<title>JavaScript Demo 1</title>
</head>
<body>
<h1>JavaScript Demo 1</h1>
<Script type=”text/javascript”>
document.write(‘<h2>Welcome to my tutorial></h2>’);
</script>
</body>
</html>

Alternatively you can create a JavaScript file and referencing it from a HTML document, as follows:

Open notepad and enter the following line

document.write(‘<h1>Welcome to my tutorial</h1>’)

save the file as j01.js and save it in the folder jscript

Now use notepad to create the following HTML file

<html>
<head>
<title>Javascript Demo 1</title>
</head>
<body>
<h1>JavaScript Demo 1</h1>
<script src=”jscript/j01.js”></script>
</body>
</html>

The <script> element is used to load the JavaScript file into the page using the attribute src, which link to the path of the script that we have created.

Comparing the two methods, it is always better to create the JavaScript file than embedding it into the HTML document as it made debugging simpler. If errors occur you just need to edit the JavaScript file. Further, you can reuse the script in another part of the document or other HTML documents.