In HTML pages, JavaScript can be implemented using the HTML Tags <script> . . . </script>. The script codes are to be written within these <script> . . . </script> tags. It is suggested to keep the script portion within the <head> tag in an HTML page. However, the same can be placed anywhere within web page.
The <script> tag tells the browser to take all the text between these tags as a script and interpret / execute them accordingly.
Syntax:
The script tag has two important attributes –
Language – to specify scripting language like JavaScript. Now in the recent versions of HTML (and XHTML, its successor) it is not used.
Type – Indicates the scripting language in use and for JavaScripts, it shall be set to "text/JavaScript".
In accommodating these attributes, the script tag will be like –
Syntax:
Example1: Let’s have a code, to simply display "Hello! How're you?"
Code:
Output:
To start working with JavaScript, we must know the basic code writing rules; some of them are defined as under:
Semicolons: Statement terminator: In JavaScript, a semicolon (;) character is placed after each statement if we want to write multiple statement in one single line.
For example:two variables in one single line:
We may omit the semicolon, if each of the statements is placed on a separate line. For example, the above code can also be written without semicolons as:
However, it is suggested to use semicolons after statement as a good programmer.
Case Sensitivity: JavaScript is a case-sensitive language i.e. lower case and upper case letters have different meaning. Hence keywords, variables, function names and any other identifiers must always be write and used properly keeping the case of the letter.
For example: var1 and Var1 have different meanings in JavaScript.
Comments in JavaScript: JavaScript supports two methodologies to specify comments.
Single line Comment: Any text content written after // is treated as a comment and is ignored by JavaScript. All the content written after // till the new line is ignored.
Multi line Comment: Any text between the characters /* and */ is treated as a comment. This may span to multiple lines or in single line.
In accommodating these attributes, the script tag will be like –
Syntax:
A sample code:
See how comments are ignored by the JavaScript interpreter
Output: