# VirtualMV/JavaScript/Starting/Layout and syntax

## JavaScript layout and syntax (rules)

• Ending Statements with a Semicolon?
• Semi-colons are used to separate pieces of code.
• Some languages like C++ and PHP require semi-colons, others (like JavaScript) are flexible - using a new line as an alternative. They are an important part in some statements (like it..then..else, and switch), and can be used to put multiple statements per line. Strict JavaScript requires semicolons. It is probably a good idea to get used to using them particularly if you want to progress to other languages.
• JavaScript is Case Sensitive
• This creates heaps of problems when you first start!!!
• White Space doesn't count!
• To Break a line of Code in the middle of a string use \, (Note next line has to start at column 1) for example:
document.write("Hello \
World!");
• Alternatively you could concatenate (join) the string
document.write("Hello " +
"World!");
• Inserting special characters (use \)
document.write ("You \& I sing \"Happy Birthday\".");
intSum = intA + intB;  //calculating the sum
/* This is a comment block on one line */
/* This is a comment block.
It contains
several lines
*/
alert("This is a message")

### External Script (js1_03)

<html>
<script type="text/javascript" src="js1_03.js"></script>
</html>

js1_03.js contains

document.write("This script is external");

### Variables

Rules for Variable names:

• Variable names are case sensitive
• They must begin with a letter or the underscore character
• Creating variables
var strName = "some text";
strName1 = "some text";
var intTotal = 400;
• using var is optional (it is good practice to use var)
• When you declare a variable within a function, the variable can only be accessed within that function. When you exit the function, the variable is destroyed. These variables are called local variables.
• If you declare a variable outside a function, all the functions on your page can access it. The lifetime of these variables starts when they are declared, and ends when the page is closed.
• If you redeclare a variable it loses its initial value.

### Prompt (JavaScript 1_04)

• The prompt object is a way that user input can be obtained and assigned to a variable... well almost! Microsoft in Internet Explorer (from version 7) have disabled this functionality, when the prompt command is called from a page on the Internet (Hunlock, 2007).[1]

#### A Prompt example

(Works in most Internet browsers. Does not work in Internet Explorer 7.x)

<html>
<title>Hello</title>
<script type="text/javascript" >
<!--
document.write("Hello " +strName +" welcome to the world \
of JavaScript");
//-->
</script>
</html>