Where to write JavaScript Code

Where to write JavaScript Code
Where to write JavaScript Code

Where to Write JavaScript codes

It is a big question that where to write JavaScript codes in our project. So we can write JavaScript codes at different places by two ways.

1)    JavaScript codes can be written in an HTML file within a script tag.

2)    JavaScript codes can be written in a .js file.

To visit the  Official website of JavaScript Click here

JavaScript – Placement in HTML File

JavaScript  codes could be written in   any section of  an HTML document. However the most recommended  ways to place JavaScript in an HTML file are as under −

  • Script in <head>…</head> section.
  • Script in <body>…</body> section.
  • Script in <body>…</body> and <head>…</head> sections.
  • Script in an external file and then include in <head>…</head> section.

Let us see, how JavaScript codes can be placed at different places.

JavaScript in <head>…</head> section

Place the  script in the head section if you wish to  run on some event,  when a user clicks on a button −

<!doctype html>
<html> 
<head>
<script type="text/javascript">
function sayHello() {

alert("Hello World");
}
</script>
</head>
<body>
<input type="button" onclick="sayHello();" value="Say Hello" />
</body>
</html>

JavaScript in <body>…</body> section

If you want to run script when page loads and the script generates page content, then the script should be placed  in the <body> portion of the document. No function needs to be defined for  using JavaScript. Take a look at the following code.

<!DOCTYPE html>
<html>

<body>

    <h2>JavaScript when placed in Body of a document</h2>

    <p id="para">A Paragraph</p>

    <button type="button" onclick="paraFunction()">Try it</button>

    <script>
        function paraFunction() {
            document.getElementById("para").innerHTML = "It will change the paragraph content.";
        }
    </script>

</body>

</html>

JavaScript in <body> and <head> Sections

You can put your JavaScript code in <head> and <body> section altogether as follows −

<!Doctype html>
<html>

<head>     
    <script type="text/javascript">
        function sayHello() {
            alert("Hello India");
        }  
    </script>
</head>

<body>
    <script type="text/javascript">
        document.write("Hello World");

    </script>
    <input type="button" onclick="sayHello()" value="Say Hello" />
</body>

</html>

 

Note: Placing scripts at the bottom of the <body> element improves the display speed, because script interpretation slows down the display.

JavaScript in External File

In the previous section,  script tag was used internally . You can also  create  an external JavaScript file with all scripting codes and include it in your HTML file.  The main benefit of this approach is to reuse the JavaScript codes extensively and same file can be used in multiple HTML files without re-writing the codes again and again.

A file name with extension .js is created for external JavaScript file. This file  can be included  as an external JavaScript file in your HTML code within script tag with  src attribute.

<!Doctype html>
<html>  

<head>     
    <script type="text/javascript" src="jsfile.js"> </script>  
</head>      

<body>      .......   </body>

</html>

in the  example below , create a file hello.js and write the content as in  file and where  sayHello function has been defined .

Contents of hello.js

function sayHello() {   alert("Hello India");}

 

Code for HTML File

<!Doctype HTML>
<html>
    <head><script src="/hello.js"></script></head>

<body>
    <input type="button" onclick="sayHello();" value="Say Hello"> 
</body>

</html>

Advantages of External JavaScript

Scripts defined  in external files has some advantages:

  • It separates HTML and code
  • Since both HTML and JavaScript codes remain in different files so it is easy to read and maintain codes.
  • Caching of  JavaScript files speeds up page loads significantly.

What is JavaScript and ECMASCRIPT

JavaScript

JavaScript was previously known as LiveScript, but Netscape changed its name to JavaScript.  JavaScript was first showcased by Netscape 2.0 in 1995 with the name LiveScript. Its general-purpose codes has been embedded in Netscape, Internet Explorer, and other web browsers.

NOTE: The standard of scripting languages like JavaScript is ECMAScript.

ECMAScript

The full name of of ECMA is European Computer Manufacturer’s Association. ECMAScript is a Standard for all scripting languages such as JavaScript, JScript, etc. It specifies a trademark scripting language specification. JavaScript is a scripting programming language based on ECMAScript which is a standard for all scripting languages like JavaScript, JScript etc. Still  JavaScript is one of the most widely used implementations of ECMAScript.

So, let us write our Hello world program in JavaScript

<!Doctype html>
<html>
<body>
<script language = "javascript" type = "text/javascript">
document.write("Hello World!")
</script>
</body>
</html>

The result of the above program would be like this.

File Extension

JavaScript file’s default extension is .js but its code could be included in .html files.

White spaces and Line Breaks

JavaScript programs ignore spaces, tabs, and newlines  in JavaScript programs. So spaces, tabs, and newlines can be used freely in a program and you are free to format and indent your programs in a neat and consistent way that makes the code easy to read and understand.

Semicolons are Optional

A one line statements in JavaScript  normally ends with a semicolon character, just as they are in C, C++, and Java.  In JavaScript, use of  semicolon can be omitted when each of the statements are placed on a separate line. For example, a single line code can be written without semicolons.

<script language="javaScript" type="text/javaScript">   
 var1 = 10     
 var2 = 20   
 
 </script>

 

But when written in a single line as mentioned below use of semi colon is must −

<script language="javascript" type="text/javascript">
 var1 = 10; var2 = 20;   
 </script>

Note − As per best practice always use semicolons at the end of a statement .

Case Sensitivity

JavaScript is a case-sensitive language. Hence the language keywords, , function names, variables and any other identifiers should always be typed with a consistency.

So the identifiers x and X will signify different identification  in JavaScript.

NOTE − A due precaution should be taken while writing variable and function names in JavaScript.

Comments in JavaScript

Comments is a descriptive text added by a programmer to give additional information about the program. JavaScript allows both C-style and C++-style of  comments, Thus −

  • A Single line comment in JavaScript starts with  // and everything till the end of a line is treated as a comment and is ignored by JavaScript.
  • Multi line comments enclosed between special characters /* and */  and is treated as a comment. This may span single or multiple lines.
  • JavaScript also recognizes the HTML comment opening sequence <!–. JavaScript treats this as a single-line comment, just as it does the // comment.
  • The HTML comment closing sequence –> is not recognized by JavaScript so it should be written as //–>.

Hope you have read this article and found it informative and helpful. Pl do comment and share  it . To get immediate notifications to my future articles subscribe it.

You may also like these topics:     Let us Learn JavaScript from Step By Step

5 1 vote
Article Rating
Subscribe
Notify of
guest

4 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
trackback
3 years ago

[…] Where to write JavaScript Code […]

trackback
3 years ago

[…]                            Where to write JavaScript Code ,         How to Generate Output in JavaScript […]

trackback
3 years ago

[…]                            Where to write JavaScript Code ,         How to Generate Output in JavaScript […]

trackback
3 years ago

[…] Let us Learn JavaScript from Step By Step                How To Enable JavaScript in Browsers               Where to write JavaScript Code […]

Please Subscribe to Stay Connected

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

DigitalSanjiv will use the information you provide on this form to be in touch with you and to provide updates and marketing.
Share via
Copy link
Powered by Social Snap