PROWAREtech
JavaScript: Tutorial - A Guide to JavaScript - Page 02
Script Placement
It used to be that all <script>
elements were placed within the <head>
element on a document:
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Document</title>
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
</head>
<body>
<!-- content goes here -->
</body>
</html>
This means that all of the JavaScript code must be downloaded, parsed, and interpreted before the page begins
rendering on the browser. This can result in a delay if there is a large amount to download and parse. Because
of this, the modern technique is to place the scripts inside the <body>
element after the
document's content.
<!DOCTYPE html>
<html>
<head>
<title>Example HTML Document</title>
</head>
<body>
<!-- content goes here -->
<script type="text/javascript" src="script1.js"></script>
<script type="text/javascript" src="script2.js"></script>
</body>
</html>
Language Basics
Syntax
JavaScript is a case-sensitive language with a C-like syntax.
An identifier is the name of a variable, function, property, or function argument. Identifiers may be formatted with the first character being a letter, an underscore (_), or a dollar sign ($). All other characters may be numbers, letters, underscores or dollar signs.
Comments come in two varieties: single-line and block. A single line comment looks like this:
// comment
A block comment looks like this:
/*
this is
a block
comment
*/
Statements should be terminated by a semicolon. Even though it is not required, it is recommended. Some example statements:
var sum = 90 + 157;
var square = 9 * 9;
Multiple statements can be combined into a block of code using curly braces:
{
var sum = 90 + 157;
var square = 9 * 9;
}
Control statements, like if
, require code blocks when executing multiple statements.
if(true)
bVariable = false;
if(true) {
bVariale = false;
iVariable = 123;
}
Keywords may not be used as identifiers. These are:
break do instanceof typeof case else new var catch finally return void continue for switch while debugger function this with default if throw delete in try
Reserved words are set aside for future use and may not be used.
abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public
Classes
JavaScript supports classes. Learn about JavaScript classes.