Introduction to Javascript

JavaScript [JS]

It is a lightweight, object-oriented programming language that is used by several websites for scripting the webpages. It is an interpreted, full-fledged programming language that enables dynamic interactivity on websites when applied to an HTML document.

Features of JavaScript

  • Lightweight and interpreted language.
  • Open and cross-platform.
  • Provides good control to the users over the web browsers.
  • Procedural and protype-based language.
  • All popular web browsers support JavaScript as they provide built-in execution environments.

Adding JavaScript in HTML

There are three ways in which we can add javascript to a web page:

  • Embedding the JS code between a pair of <SCRIPT> and </SCRIPT> tag
<!DOCTYPE HTML>  
<HTML lang="en" >  
<HEAD>  
<META charset="UTF-8">  
<TITLE>Embedded JavaScript</TITLE>  
</HEAD>  
<BODY>  
<SCRIPT>  
var greet= "Hello World";  
document.write(greet);  
</SCRIPT>  
</BODY>  
</HTML>
  • Creating an external JavaScript file with the .js extension and then load it within the page through the src attribute of the <SCRIPT> tag

Let’s write a JS file named “hello.js” and place the code below:

//A function to display a message  
function sayHello()  
{  
alert("Hello World");  
}

Now, we can call this external JS file within a webpage using <SCRIPT> tag;

<!DOCTYPE HTML>  
<HTML lang="en" >  
<HEAD>  
<META charset="UTF-8">  
<TITLE>Including external JavaScript file</TITLE>  
</HEAD>  
<BODY>  
<BUTTON onclick="sayHello()"> Click Me </BUTTON>  
<SCRIPT src="hello.js"> </SCRIPT>  
</BODY>  
</HTML>
  • Placing the JavaScript code directly inside an HTML tag using the special tag attributes such as onclick, onmouseover, onkeypress, etc.
<!DOCTYPE HTML>  
<HTML lang="en" >  
<HEAD>  
<META charset="UTF-8">  
<TITLE>Inlining JavaScript </TITLE>  
</HEAD>  
<BODY>  
<BUTTON onclick="alert('Hello World')"> Click Me </BUTTON>  
</BODY>  
</HTML>