h3. Introduction to JavaScript

JavaScript was originally developed by Brendan Eichof Netscape under the name Mocha, which was later renamed to LiveScript and finally to JavaScript. JavaScript code, much like other programming languages, is made up of statements which serve to make assignments, compare values and execute other sections of code.

JavaScript:
* Is interpreted line-by-line
* Is case sensitive
* Ignores whitespaces
* Uses semicolon at the end of each statement
* Uses blocks (with curly braces)
* Uses identing in code
* Uses commenting symbols
* Uses keywords


\\

h3. Basic programming terminology

JavaScript has some basic programming terms:
|| Name || Definition || Examples ||
| Token | The smallest indivisible lexical unit of the language; a contiguous sequence of characters whose meaning would change if the characters were separated by a space. | All identifiers; literals like _3.14_ and _'This is a string'_. |
| Literal | A value found directly in the script. | _3.14_, _'This is a string'_ |
| Identifier | The name of a variable, object, function or label. | _x_, _myValue_, _userName_ |
| Operator | Tokens that perform built-in language operations like assignment, addition and substraction. | _=_, _+_, _\-_, _\*_ |
| Expressions | A group of tokens; often literals or identifiers, combined with operators that can be evaluated to a specific value. | _2.0_, _'This is a string.'_, _(x + 2) * 4_ |
| Iterations | Executing the same set of instructions a given number of times or until a specific result is attained. | _for (var i = 0; i < 10; i++) // set i = 0, if i < 10, add 1 to i_ |
| Statement | An imperative command, usually causes the state of the execution environment to change. | _var x = x + 2;_ \\
_if(x == 4) {_ \\
_alert('It is x');_ \\
_}_ |
| Keyword | A word that is part of the language, may not be used for identifiers. | _while_, _do_, _function_, _var_ |
| Reserved word | A word that may become part of the language; may not be used as identifiers. | _break_, _import_, _public_ |

{note:title=Note}
For a complete list of reserved words, please check the TODO section.
{note}

\\

h3. Execution order

JavaScript is interpreted (executed) line-by-line as it is found in a piece of code (script)


\\

h3. Case sensitivity

JavaScript is case sensitive, meaning that capital letters are distinct from their lowercase counterparts.

For example, the following identifiers refer to separate, distinct values:
* result
* Result
* RESULT

\\
Case sensitivity applies to all aspects of the JavaScript language:
* Keywords
* operators
* Variable names
* Event handlers
* Object properties


\\

h4. Lowercase keywords

All JavaScript keywords are lowercase. For example, when you use a feature like an _if_ statement, make sure that you type _if_ and not _If_ or _IF_.


\\

h4. Camel casing (camel-back)

JavaScript uses the camel casing (mixed casing) naming convention for functions, methods and properties. If a name is one word, then the name is made of all lowercase characters. If more words are used to form a name, the first word is lowercase followed by the next word(s) which all start with a capital letter.

Here some examples:
* displayType
* getTimeZoneOffset
* round
* toFixed

{note:title=Note}
No spaces and punctuations are using with forming these names.
{note}

\\

h3. Whitespace

JavaScript applies these rules to the use of the whitespace in coding.

\\

h4. Whitespace ignored

JavaScript ignores those characters that take up space on the screen without visual representation or without necessary meaning.

For example:
{code}
x = x + 1
{code}
Can be written like:
{code}
x=x+1
{code}
or:
{code}
x = x + 1
{code}

\\

h4. Whitespace not ignored (exception)

However, most operations other than simple arithmetic functions require a space to make their meaning clear.

For example:
{code}
s = typeof x
{code}
and:
{code}
s = typeofx
{code}
do not have the same meaning. The first statement invokes the _typeof_ operator on a variable _x_ and places the result in _s_. The second statement copies the value of a variable called _typeofx_ into _s_.

\\
Whitespaces within a string, between single or double quotes, are preserved. For example:
{code}
var s = 'This spacing is      preserved.';
{code}

TODO Whitespaces inside regular expressions (RegExp)


\\

h3. Using semicolons

A semicolon indicates the end of a JavaScript statement. You can use a semicolon for:

* A single statement
* Multiple statements on one line
* Multiple statements on multiple lines.


h4. Single statement

Example:
{code}
x = x + 1;
{code}

h4. Multiple statements on one line

Example:
{code}
x = x + 1; y = y + 1; z = 0;
{code}

h4. Multiple statements on multiple lines

Example:
{code}
x = x + 1;
y = y - 1;
{code}

{note:title=Note}
You do not need to use a semicolon for the last statement of a method (script).
{note}


h3. Using curly braces

JavaScript uses curly braces _{}_ to group a list of statements together into one larger statement, known as a block statement.

Here an example of statements that make up the body of a function:
{code}
function add(x, y) {
	var result = x + y;
	return result;
}
{code}

Here is an example of more than one statement to be executed:
{code}
if (x > 10) {
	x = 0;
	y = 10;
}
{code}

\\

h3. Indenting

Here is an _if else_ example to show standard identing in JavaScript code:
{code}
var x = 5;
if (x > 1) {
	if (x > 2) {
		alert('x > 2');
		alert('Yes, x > 2');
	}
} else {
	alert('x <= 1');
	alert('Yes, x <= 1');
}
alert('Moving on.');
{code}

\\
Here is an explanation, step-by-step of the identing example:
|| Line || Step || Indenting || Semicolon || Purpose ||
| 1 | var x = 5; | No | Yes | Declare variable. |
| 2 | if (x > 1) { | No | No | First _if_ condition with open curly brace for block statement. |
| 3 | if (x > 2) { | Forward | No | Second _if_ condition with opening curly brace for block statement. | | 4 | alert('x > 2'); | Forward | Yes | First statement for second _if_ condition. | | 5 | alert('Yes, x > 2'); | No | No | Second statement for second _if_ condition. | | 6 | }\\ | Back | No | Close curly brace for block statement of second _if_ statement. |
| 4 | alert('x > 2'); | Forward | Yes | First statement of second _if_ condition. |
| 7 | } else { | Back | No | Close curly brace for block statement of first _if_ condition, _else_ condition and open curly bracket for block statement. | | 8 | alert('x <= 1'); | Forward | Yes | First statement for _else_ condition. | | 9 | alert('Yes, x > 2'); | No | Yes | Second statement for _else_ condition. | | 10 | }\\ | Back | No | Close curly brace for block statement of _else_ condition. |
| 11 | alert('Moving on.'); | No | Yes | Final statement of the block. |


\\

h3. Commenting

An important aspect of good JavaScript code (and actually all code) is commenting. Commenting means:
* You can insert remarks and commentary directly into your code.
* Included comments will be ignored by the JavaScript interpreter.

\\

h4. Single line comments

Single line comments begin with a double forward slash _//_. The interpreter will ignore everything from that point until the end of the line.

Example:
{code}
var count = 10; // holds a number of items
{code}

\\

h4. Multiple line comments

Multiple line comments (similar to C programming) are enclosed between forward slash and asterix _/_ *at the beginning of the comment and an asterix and forward slash* _/_ at the end of the comment. Everything in between is ignored by the interpreter.

Example:
{code}
/* Both x = 0 and y = 10
   statements will be executed
   when the if statement is true.
*/
if (x > 10) {
	x = 0;
	y = 10;
}
{code}
{note:title=Note}
It's not possible to nest comments and will result in an error.
{note}

h3. Keywords

Keywords are part of the set of JavaScript reserved words.

{note:title=Note}
For a list of reserved words, please check the "JavaScipt reserved words" section.
{note}

\\

h4. new

the keyword _new_ enables you to create your own object and is used for an object's constructor.

Example:
{code}
var myArray = new Array();
myArray[0] = "Thomas";
myArray[1] = "Bob";
{code}

TODO: reference to "Object references"


h4. var

The keyword _var_ is used to declare variables.

Example:
{code}
var x = 2;
{code}

\\

h3. JavaScript grammar

Here are the main elements of JavaScript grammar:
* Variables
* Data types
* Operators
* Expressions
* Statements
* Objects
* Properties
* Functions and methods

\\

h4. Variables

Variables are used to stored data. Each variable has a name, called its identifier. Variables are declared in JavaScript using the _var_ keyword. This keyword allocates storage space for new data and indicates that a new identifier is in use.

{note:title=Note}
You should not use variables without first declaring them. Using a variable on the right-hand side of an assignment without first declaring it will result in an error.
{note}

\\

h4. Introduction to declaring variables

When you declare a variable you can do that with or without assigning a value to it.

This example shows how to declare a variable without assigning a value to it:
{code}
var x;
{code}
This example shows how to assign a value when declaring a variable:
{code}
var x = 0;
{code}
You can also declare multiple variables by using one _var_ statement:
{code}
var x, y = 1, z;
{code}

\\

h4. Data types

JavaScript knows two categories of data types:
* Primitive (basic) data types
* Composite data types

\\

h5. Primitive data types

These are primitive or basic data types, which contain one kind of data, for variables:
* String
* Number
* Boolean
* Undefined
* NULL

\\

h6. String

A string is a list of characters. A string literal is indicated by enclosing characters in single quotes _'_ or double quotes _"_.

For example:
{code}
var myString = 'JavaScript has strings.";
{code}
Any alphabetic, numeric or punctuation characters can be placed in a string.

However, there are some exceptions known as escape codes. An escape code (also called escape sequence) is a small amount of characters preceded by a backslash that has a special meaning to the JavaScript interpreter. Escape codes allow you to enter special representative characters witout typing them directly into your code.

Let's say that you want to declare two lines of text in a variable:
{code}
var myString = 'This is the first line.
This is the second line';
{code}
The way this is done will result in a syntax error, because JavaScript interprets the second line as a separate statment. The correct way to do this is by using an escape character:
{code}
var myString = 'This is the first line.\nThis is the second line.";
{code}

Here a list of escape codes:
|| Escape code || Value ||
| \b | Backspace |
| \t | Horizontal tab |
| \n | Line feed (new line) |
| \v | Vertical tab |
| \f | Form feed |
| \r | Carriage return |
| \' | Single quote |
| \" | Double quote |
| \\ | Backslash |
| \OOO | Latin-1 character represented by the octal digits OOO. The valid range is 000 to 377. |
| \xHH | Latin-1 character represented by the hexidecimal digits HH. The valid range is 00 to FF. |
| \uHHHH | Unicode character represented by the hexidecimal digits HHHH. |

\\

h6. Numeric

Numbers are integers or floating-point numeric values:
{code}
var myNumber = 3.14;
{code}

\\

h6. Boolean

Boolean data types take on one of two possible values: _true_ or _false_. A boolean literal is indicated by using these values directly in the code:
{code}
var myBoolean = true;
{code}

\\

h6. Undefined

An undefined data type is used for variables and object properties that do not exist or have not been assigned a value. The only value an undefined type can have is _undefined_:
{code}
var x;
var x = String.noSuchProperty;
{code}

\\

h6. NULL

The NULL value indicates an empty or non-existent value, but the data type is defined. The only value a NULL data type can have is NULL:
{code}
var x = null;
{code}
{note:title=Note}
When undefined and NULL data types are being compared, the result will be true.
{note}

\\

h5. Composite data types

Composite data types are made up of strings, numbers, booleans, undefined values, null values and even other composite types. These are the three composite types:
* Object
* Array
* Function

\\

h6. Object

An object can hold any type of data and is the primary mechanism by wich tasks are carried out. Data contained in an object are properties for the object. Properties are accessed with the dot operator _._ followed by the property name:
{code}
objectName.propertyName
{code}

\\

h6. Array

The array data type is an ordered set of values grouped together under a single identifier. The easiest way to create an array is to define it as a standard variable and then group the set of values in brackets:
{code}
var myArray = [1, 5, 68, 3];
{code}
Arrays can contain data of different data types:
{code}
var myArray = ['Bob', 5, true, x];
{code}
To create an array with no length:
{code}
var myArray = new Array();
{code}
To create an array with a predetermined length, but no specific data:
{code}
var myArray = new Array(4);
{code}
The elements of an array are accessed by providing an index value within brackets. In the following example variable _x_ equals _Bob_ and variable _y_ equals _true_:
{code}
var myArray = new Array('Bob', 5, true, x);
var x = myArray[0];
var y = myArray[2];
{code}

\\

h6. Function

Functions are used to keep code that performs a particular job in one place, making the code reusable. In Servoy, built-in functions are accessible from the method editor.


h5. Weak typing

One of the major differences between JavaScript and other programming languages is that JavaScript is weakly typed. This means that the type of variable is inferred from the variable's content. As a result, the data type can change the moment you put data into the variable of another type than it previously contained.

For exampe, first we assign a string value to the variable and after that we assign a numeric value to it:
{code}
var x = 'Hello';
x = 5.25;
{code}

\\

h4. Operators

Basic operators include:

* Arithmetic
* Increment and decrement
* Logical
* Comparison
* Tertiary statement


h5. Arithmetic

Here are the common arithmetic operatros: