## 5. Javascript Language Part 1

### Learning Objectives

By the end of the session you should:

- understand the Javascript types: numbers, strings, booleans
- be able to declare, initialise and assign variables
- be able to formulate expressions: arithmetic, relational and logical
- know that there are a range of built-in functions for maths and string manipulation
- understand the syntax of function declarations and function calls
- understand the difference between variables in local scope and global scope

### Topics

- Types & literal values
- Variables & assignment
- Expressions
- Function declarations and calls

##### Numeric

**Numeric** values in Javascript hold real ("floating-point") numbers, approximately in the range

-10^{308} … -10^{-324}, 0, 10^{-324} … 10^{308}

Numbers are stored with an approximate precision of 15 digits.

Whole numbers (integers) may only be stored exactly between -9007199254740992 … 9007199254740992.

Examples of number literals:

`23, -102, 2.678, 3.45E10, 5.67E-4`

##### String

Javascript **strings** are sequences of zero or more Unicode characters, for example:

"Hello", 'One Two Three', "中国", "juːnɪkəʊd", "A", ""

Note that "A" is a string containing one character, and that "" is a string containing no characters.

Strings may be enclosed in single or double quotes. To include a quote mark within a string, you can use `\'` or `\"`.
To include a "newline" in a string, you can use `\n`.
To include backslash in a string, you can use `\\`.

##### Boolean

A **boolean** value can only be either `true` or `false`.

##### Object

All other elements of Javascript, such as functions or elements of web pages are called **objects**. We will see that all objects can be manipulated in Javascript.

Variables are named locations in memory where you can store information (in the form of numbers, strings, booleans or objects).

Variables are identified with **names**. The name of a variable is a combination of letters, digits, the underscore character (_) and the dollar sign ($), although the first character may not be a number. The case of letters matters, the variable `fred` is different from `Fred`. A number of words are reserved for the language syntax and may not be used to name variables (e.g. "function", "var", "true", "false").

Variables should be **declared** before use. This guards against typing mistakes! Normally you declare a variable at the same time as you first use it. It is good practice to allocate each variable a value at declaration, otherwise the contents of the variable is undefined.

Variables can be declared with the `var` statement:

var mynumber; var mystring; var myboolean;

You do not need to specify the type of the variable in the declaration. Javascript will assign a type when you first use it, and will change the type as required. To initialise each variable to a specific value in the declaration, use the syntax:

var mynumber=100; var mystring="Javascript"; var myboolean=false;

Once a variable has been declared you can change its contents using an **assignment statement**:

variable=expression

For example:

mynumber=25; mystring="Hello"; myboolean=true;

Note that assignment is not the same as the test for equality. You should read these statements as "mynumber becomes 25", "mystring becomes Hello", "myboolean becomes true".

Expressions are defined next.

Expressions are combinations of literal values, variable values and operators which can be evaluated to give an arithmetic, string or boolean result.

##### Arithmetic

The most common arithmetic operators

Name | Example | Description |
---|---|---|

+ | a+b | Add numbers, Concatenate strings |

- | a-b | Subtract |

* | a*b | Multiply |

/ | a/b | Divide |

% | a%b | Modulus (Remainder after integer division) |

() | a*(b+c) | Group |

++ | a++ | Increment |

-- | a-- | Decrement |

##### Relational

The most common relational operators

Name | Example | Description |
---|---|---|

< | a<5 | Less than |

<= | 0<=b | Less than or equal |

> | c>0 | Greater than |

>= | 100>=a | Greater than or equal |

== | a==10 | Equal |

!= | b!=100 | Not equal |

##### Logical

The most common logical operators

Name | Example | Description |
---|---|---|

&& | (1<=a)&&(a<=10) | And |

|| | (a<1)||(a>10) | Or |

! | !((a<1)||(a>10)) | Not |

##### Mathematics

The most common math functions. These properties and methods are accessed through the global "Math" object.

Name | Example | Description |
---|---|---|

Math.PI | a=2*Math.PI | Value of π |

Math.abs(x) | a=Math.abs(b) | Returns the absolute value of a number. |

Math.ceil(x) | ival=Math.ceil(rval) | Returns the smallest integer greater than or equal to a number. |

Math.exp(x) | e10=Math.exp(10) |
Returns e^{x}, where x is the argument, and e is Euler's number (2.718...), the base of the natural logarithm. |

Math.floor(x) | ival=Math.floor(rval) | Returns the largest integer less than or equal to a number. |

Math.log(x) | l=Math.log(10) |
Returns the natural logarithm (log_{e}, also ln) of a number. |

Math.log10(x) | l=math.log10(50) |
Returns the base 10 logarithm (log_{10}) of x. |

Math.max([x[,y[,…]]]) | c=Math.max(a,b) | Returns the largest of a list of numbers. |

Math.min([x[,y[,…]]]) | c=Math.min(a,b) | Returns the smallest of a list of numbers. |

Math.pow(x,y) | p=Math.pow(10,1.2) |
Returns x to the power y, that is, x^{y}. |

Math.random() | r=Math.random() | Returns a pseudo-random number between 0 and 1 (0 <= n < 1). |

Math.round(x) | ival=Math.round(rval) | Returns the value of a number rounded to the nearest integer. |

Math.sqrt(x) | r=Math.sqrt(2) | Returns the positive square root of a number. |

Math.trunc(x) | ival=Math.trunc(rval) | Returns the integral part of the number x, removing any fractional digits. |

The Math object also includes all the usual trigonometric functions: Math.sin(), Math.cos(), Math.tan(), etc.

##### String methods

A *method* is the name given to a function that is tied to a particular variable or expression. To these string methods
you must start with a string object and then apply these functions using the "dot" operator. Here is an example. The `toLowerCase()` method returns the string converted to lower case, but given a string variable with the name `mystring` you would not write `toLowerCase(mystring)`, but instead `mystring.toLowerCase()`. This is because the toLowerCase() method belongs to the class of string objects rather than being a global function.

These are some of the more frequently used string methods:

Name | Example | Description |
---|---|---|

charAt(index) | ch=str.charAt(5) | Returns the character at the specified index. Note that the first character has index 0. |

indexOf(term) | idx=str.indexOf("x") | Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. |

lastIndexOf(term) | idx=str.lastIndexOf("ABC") | Returns the index within the calling String object of the last occurrence of the specified value, or -1 if not found. |

slice(start,stop) | xtr=str.slice(2,4) | Extracts a section of a string and returns a new string. Extraction starts at character index start and ends just before character index stop. If stop is missing, returns rest of string to end. |

substr(start,num) | xtr=str.substr(2,2) | Returns the characters in a string beginning at the specified location through the specified number of characters. If num is missing, returns rest of string to end. If start is negative the index is counted from the end of the string backwards. |

toLowerCase() | lwr=str.toLowerCase() | Returns the string value converted to lower case. |

toUpperCase() | upr=str.toUpperCase() | Returns the string value converted to uppercase. |

In addition you can obtain the length of any string expression using its `length` property:

var str="Hello."; console.log("length of string str is "+str.length);

Would print 'length of string str is 6'.

##### The `eval()` function

The `eval()` function takes a string argument and evaluates it as if it were a JavaScript expression. This can be useful when you want to test how expressions are evaluated. You can experiment with the use of `eval()` in the form below, which has the following event handler at its heart:

function button1click() { document.getElementById("answer").innerHTML = eval(document.getElementById("expression").value); }

Javascript Expression Evaluator

=

##### Function definition

A function is a block of Javascript code which is given a name and an optional set of parameters. When called, the code in the function is executed and may return a value.

A function declaration has the syntax:

functionname(parameter-list) {statements}

The name is used to identify the function and must be unique in the script. The parameter list is a comma-separated list of *dummy variables*, these are the names used within the function for the expressions passed in the function call. The block of statements must be bracketed with {} and statements are separated from one another by semi-colons ";". If you want the function to return a value use the statement `return expression`. When this statement is executed the function call is terminated and the value of the expression is returned to the calling expression.

Here are some example definitions:

function doprint(x) { console.log("Value of variable = " + x); } function square(x) { return(x*x); } function hypot(a,b) { var a2=a*a; var b2=b*b; return(Math.sqrt(a2+b2)); }

Functions are called using the syntax ` name ( expression-list )`. Items in the expression list are separated by commas. How the functions above may be called:

var x=10; doprint(x); var y=square(10); var h=hypot(x,y);

Functions may also be defined using an assignment statement with the syntax:

name= function (parameter-list) {statements}

for example:

square = function (x) { return(x*x); }

The two forms of function declaration are equivalent.

##### Variable scope

When variables are declared within a function, they may only be accessed within that function, they do not exist except when the function is being called. We say that these variables have *local scope*. Variables declared outside any function can be accessed anywhere, both within and outside function blocks. We say that such variables have *global scope*.

Global variables are important as a means to preserve data values between events. While local variables are initialised and their old contents lost each time their function is called; global variables are initialised when the page is loaded and retain their values until the page is unloaded.

##### Some useful built-in functions & methods

Name | Example | Description |
---|---|---|

eval | a=eval("123*456") | Evaluates the Javascript code in the given string |

parseInt | ival=parseInt("123") | Converts a string to an integer |

parseFloat | rval=parseFloat("3.14159") | Converts a string to a floating point number |

toExponential(n) | str=num.toExponential() | Formats a number in exponential notation, the optional argument sets the number of digits after the decimal point |

toFixed(n) | str=num.toFixed(3) | Formats a number with n digits after the decimal point |

toPrecision(n) | str=num.toPrecision(10) | Formats a number using n characters (1<=n<=21) |

toString() | str=num.toString() | Converts a number to a string |

### Resources

- Lynda video tutorials at UCL. Particularly "JavaScript Essential Training" and "Introducing the JavaScript language".
- Javascript for Beginners - video series from Microsoft.
- Javascript Tutorial - from W3Schools.
- Javascript quick guide - a one page summary of the most important features of JavaScript.

### Exercises

- Implement demonstration demo5-1.html: JavaScript Expression Evaluation. Use this to demonstrate the following:
- Arithmetic operator precedence
- String concatenation
- Math functions
- String methods
- Implement the adding machine application demo5-2.html. Modify the code ("ex5-2.html") to allow multiplication as well as addition, and also add a Reset button to reset value to zero.
- Implement the string method demonstration demo5-3.html. Modify the code ("ex5-3.html") to also demonstrate the indexOf() and lastIndexOf() methods too.
- Write an interactive application ("ex5-4.html") that inter-converts between linear values and decibels. The formulae are: db=20.log
_{10}(linear) and linear=10^{db/20}. - Write an interactive application ("ex5-5.html") that inter-converts between centimetres and feet & inches. The formulae are: inches=cm/2.54 and cm=2.54*inches.
- Write an interactive application ("ex5-6.html") that displays a random alphabetic letter when a button is pressed. Hint: generate a random integer between 1 and 26 with
`Math.random()`, then select a character from the alphabet with the string method`charAt(index)`.

### Homework

- Complete the exercises you did not finish in class.
- Watch an introductory video on the syntax of the JavaScript language such as Introducing the JavaScript language.
- Work through the part of any text tutorial on JavaScript that covers the topics we have addressed today, such as the W3Schools tutorial or JavaScript quick guide.
- The JavaScript
`Date`object can be used to get the current date and time. Read up about the Date object on the web then write a program that displays the current day and time in the format: "Sat Oct 31 2015 14:15:31". Be sure to nicely style the display of the date. Advanced: you can use the`setTimeout()`function to update the date and time each second; read about how to do this on the web, then update your program to turn it into a dynamic clock, like this: - Upload your answers to your exercises area on the course web space.

Word count: . Last modified: 11:17 28-Oct-2016.