Home >>Javascript Tutorial >Javascript Syntax

Javascript Syntax

Javascript Syntax

Execution of JavaScript can be done by placing JavaScript statements within the HTML tags in a web page. JavaScript is an easy language when it comes to coding.

Generally there are three places where you can put the JavaScript code:

  • Inside Body Tag
  • Inside head
  • External JavaScript file
Here is an example to understand this from an initial level:
<script type="text/javascript">  
document.write("PHPTPOINT is the place to study javascript easily");  
</script>   

Using the script tag signifies that we are using JavaScript

Javascript Syntax : Code Between The Body Tag

In the above explained example there is a depiction of the dynamic content using the javascript. Here is another example displaying alert box.

 <html> 
<head>  
<title>JavaScript Inside Body</title>
</head>  
<body>
<script type="text/javascript">  
function msg()
{  
alert("Hello phptpoint");  
}  
</script>  
</body>  
</html> 

Javascript Syntax : Code Between The Head Tag

We have seen the example of alert code inside the body tag, now let's see the example of JavaScript alert OR displaying result inside the head tag.
In order to create a function in JavaScript, the function must be written with function_ name as shown in the example below.

An event is needed to call a function. In the following example on click even is used to call msg () function.

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

External JavaScript file

With JavaScript a external JavaScript file can be created and can easily be embedded into many HTML pages. Since a single javascript file can be used in various HTML pages hence, it provides code re usability.

In order to save a javascript file, .js extension must be used. To increase the speed of the webpages, it is recommended to embed all the JavaScrip file in to a single file.

Here is a simple example:
function msg()
{  
 alert("Hello phptpoint");  
}  

The above file will be saved with the name myscript.js

Here is another example that includes the External JavaScript in to HTML page. This code calls the JavaScript function on button click.

<html>  
<head>  
<title>External Javascript Example-Phptpoint</title>
<script type="text/javascript" src="myscript.js"></script>  
</head>  
<body>  
<p>Welcome to Phptpoint</p>  
<input type="button" value="click" onclick="msg()"/>  
</body>  
</html>  

No Sidebar ads