NETB131 Programming Project
Programming language JavaScript
An overview

Volen Yordanov Ilarionov, F39998


Navigation:
1. History and Special Features
2. "Hello World" Program
3. Fundamental Data Types and Assignment Operators
4. Basic Control Flow
5. Functions
6. Arrays
7. Compilers
8. Projects and software in JavaScript
9. Standard
10. References

1. History and Special Features

    JavaScript is a scripting language most often used for client-side web development. It was the originating implementation of the ECMAScript standard. As such, it is a dynamic, weakly typed, prototype-based language with first-class functions.

JavaScript was influenced by many languages and was designed to have a similar look to Java, but be easier for non-programmers to work with. The language is best known for its use in websites (as client-side JavaScript), but is also used to enable scripting access to objects embedded in other applications.

JavaScript was originally developed by Brendan Eich of Netscape under th e name Mocha, later LiveScript, and finally renamed to JavaScript. The change of name from LiveScript to JavaScript roughly coincided with Netscape adding support for Java technology in its Netscape Navigator web browser. JavaScript was first introduced and deployed in the Netscape browser version 2.0B3 in December of 1995. The naming has caused confusion, giving the impression that the language is a spinoff of Java and has been characterized by many as a marketing ploy by Netscape to give JavaScript the cachet of what was then the hot new web-programming language.

JavaScript supports all the structured programming syntax in C, e.g. if statement, while loops, switch statement, etc. One exception is scoping: JavaScript supports function-level scoping, but not block-level scoping.

2. "Hello World" Program  (^)

<html>
  <head><title>simple page</title></head>
  <body>
    <script>
      document.write('Hello World!');
    </script>
    <noscript>
      Your browser does not support JavaScript.
    </noscript>
  </body>
</html>



3. Fundamental Data Types (integer, floating point, string) and Assignment Operator  (^)

Numbers in JavaScript

Numbers in JavaScript are represented in binary as IEEE-754 Doubles, which provides an accuracy to about 14 or 15 significant digits JavaScript FAQ 4.7. Because they are binary numbers, they do not always exactly represent decimal numbers, particularly fractions.

This becomes an issue when formatting numbers for output, which JavaScript has no built-in methods for. For example:


alert(0.94 - 0.01); // displays 0.9299999999999999

As a result, rounding should be used whenever numbers are formatted for output. The toFixed() method is not part of the ECMAScript specification and is implemented differently in various environments, so it can't be relied upon.

Numbers may be specified in any of these notations:

345;    // an "integer", although there is only one numeric type in JavaScript
34.5; // a floating-point number
3.45e2; // another floating-point, equivalent to 345
0377; // an [[octal]] integer equal to 255
0xFF; // a [[hexadecimal]] integer equal to 255, the letters A-F may be upper- or lowercase

In some ECMAScript implementations such as ActionScript, RGB color values are sometimes specified with hexadecimal integers:

var colorful = new Color( '_root.shapes' );
colorful.setRGB( 0x003366 );



The Number constructor may be used to perform explicit numeric conversion:


var myString = "123.456"
var myNumber = Number( myString );
 



To convert a string to a number, you can use the JavaScript function parseInt (for conversion to an integer) or  parseFloat (for conversion to a floating-point number).

Integer data types

parseInt syntax:   parseInt( 'string' [, base] )
 


How it works:

The first argument of parseInt must be a string or a string expression. The result returned by parseInt is an integer whose representation was contained in that string (or the integer found in the beginning of the string). The second argument (base), if present, specifies the base (radix) of the number whose string representation is contained in the string. The base argument can be any integer from 2 to 36.

If there is only one argument, the number base is detected according to the general JavaScript syntax for numbers. Strings that begin with 0x or -0x are parsed as hexadecimals; strings that begin with 0 or -0 are parsed as octal numbers. All other strings are parsed as decimal numbers.

If the string argument cannot be parsed as an integer, the results will be different in different browsers (either 0 or NaN).

Examples (comments in each line give the conversion results):

parseInt('123.45')  // 123
parseInt('77') // 77
parseInt('077',10) // 77
parseInt('77',8) // 63 (= 7 + 7*8)
parseInt('077') // 63 (= 7 + 7*8)
parseInt('77',16) // 119 (= 7 + 7*16)
parseInt('0x77') // 119 (= 7 + 7*16)
parseInt('099') // 0 (9 is not an octal digit)
parseInt('99',8) // 0 or NaN, depending on the platform
parseInt('0.1e6') // 0
parseInt('ZZ',36) // 1295 (= 35 + 35*36)


Floatingpoint data types

parseFloat syntax:   parseFloat('string')


How it works:
The argument of parseFloat must be a string or a string expression. The result of parseFloat is the number whose decimal representation was contained in that string (or the number found in the beginning of the string). If the string argument cannot be parsed as a decimal number, the results will be different in different browsers (either 0 or NaN).

Examples (comments in each line give the conversion results):

parseFloat('1.45kg')  // 1.45
parseFloat('77.3') // 77.3
parseFloat('077.3') // 77.3
parseFloat('0x77.3') // 0
parseFloat('.3') // 0.3
parseFloat('0.1e6') // 100000

 Strings

Strings in Javascript are a sequence of characters. Strings in JavaScript can be created directly by placing the series of characters between double or single quotes.

var greeting = "Hello, world!";
var another_greeting = 'Greetings, people of Earth.'; 


Assignment


 
=     Assign
    +=    Add and assign
    -=    Subtract and assign
    *=    Multiply and assign
    /=    Divide and assign


Examples :

var x = 1;
x *= 3;
document.write( x );  // displays: 3
x /= 3;
document.write( x );  // displays: 1
x -= 1;
document.write( x );  // displays: 0
 



4. Basic Control Flow (conditional and loop statements)  (^)

Conditional operator:

if (expr)
{
statements;
}

else
{
statements;
}

Loop operator:

While loop
while (cond-expr) {
  statements;
}


Do while
do {
  statements;
} while (cond-expr);




Task: Input an integer number n and output the sum: 1+22+32+...+n2. Use input validation for n to be positive.

<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=windows-1251">
<title>Untitled Document</title>
<script type="text/javascript" language="javascript">
function sum() {
var num = document.getElementById('value').value;
if(num.match(/\b\d+\b/)) {
if(num > 0) {
if (num.match(/^[0-9]*?$/)) {
var sum = 0;
for(i = 1; i<=num;i++) {
if(i >= 2) {
sum += i*i;
}
}
alert('Sum is: ' + (sum+1));
} else {
alert('Not a natural number');
}
} else {
alert('Number must be greater than zero');
}
} else {
alert('Enter a number');
}
}
</script>
</head>
<body>
<form name="form1" action="?"> <input value="Enter a natural number"
id="value" type="text"> <input id="but" value="Calculate"
onclick="sum();" type="button"> </form>
Input an integer number "n" and the program will output the sum: 1+2<sup>2</sup>+3<sup>2</sup>+...+n<sup>2</sup>
</body>
</html>






5. Functions - syntax, writing and using functions, example  (^)

A function in JavaScript is a block with a (possibly empty) parameter list that is normally given a name. A function may give back a return value.
The syntax of JavaScript function is as follows:


function function_name(prameter1,parameter2, ...)
{
    JavaScript code 1
    JavaScript code 2
   ....
}


Normal function construct
function function-name(arg1, arg2, arg3) {
statements;
return expression;
}
Anonymous functions are also possible:

var fn = function(arg1, arg2) {
  statements;
  return expression;
}; 


Example: Euclid's original algorithm of finding the greatest common divisor. (This is a geometrical solution which subtracts the shorter segment from the longer):

function gcd(segmentA, segmentB) {
  while (segmentA != segmentB) {
    if (segmentA > segmentB)
      segmentA -= segmentB;
    else
      segmentB -= segmentA;
  }
  return segmentA;
}

The number of arguments given when calling a function may not necessarily correspond to the number of arguments in the function definition; a named argument in the definition that does not have a matching argument in the call will have the value undefined. Within the function the arguments may also be accessed through the arguments list; this provides access to all arguments using indices (e.g. arguments[0], arguments[1], ... arguments[n]), including those beyond the number of named arguments. Note that while the arguments list has a .length property, it is not an instance of Array; it does not have methods such as .slice(), .sort(), etc.

Basic data types (strings, integers, ...) are passed by value whereas objects are passed by reference.


6. Arrays - syntax, definition, example  (^)

    An Array is a map from integers to values. In JavaScript, all objects can map from integers to values, but Arrays are a special type of object that has extra behavior and methods specializing in integer indices (e.g., join, slice, and push).

Arrays have a length property that is guaranteed to always be larger than the largest integer index used in the array. It is automatically updated if one creates a property with an even larger index. Writing a smaller number to the length property will remove larger indices. This length property is the only special feature of Arrays that distinguishes it from other objects.

Elements of Arrays may be accessed using normal object property access notation:

myArray[1];
myArray["1"];

The above two are equivalent. It's not possible to use the "dot"-notation or strings with alternative representations of the number:

myArray.1;     // syntax error
myArray["01"]; // not the same as myArray[1]

Declaration of an array can use either an Array literal or the Array constructor:


myArray = [0,1,,,4,5];            // array with length 6 and 4 elements
myArray = new Array(0,1,2,3,4,5); // array with length 6 and 6 elements
myArray = new Array(365);         // an empty array with length 365

 

Arrays are implemented so that only the elements defined use memory; they are "sparse arrays". Setting myArray[10] = 'someThing' and myArray[57] = 'somethingOther' only uses space for these two elements, just like any other object. The length of the array will still be reported as 58.

You can use the object declaration literal to create objects that behave much like associative arrays in other languages:

dog = {"color":"brown", "size":"large"};
dog["color"]; // this gives you "brown"
 



You can use the object and array declaration literals to quickly create arrays that are associative, multidimensional, or both.

cats = [{"color":"brown", "size":"large"},
{"color":"black", "size":"small"}];
cats[0]["size"]; // this gives you "large"

dogs = {"rover":{"color":"brown", "size":"large"},
"spot":{"color":"black", "size":"small"}};
dogs["spot"]["size"]; // this gives you "small"


7. Compilers  (^)


Cardinal Javascript IDE  - Browser-based Javascript compiler

FESI (pronounced like fuzzy) is a full implementation of the first version of the EcmaScript language. EcmaScript is largely equivalent to the JavaScript language version 1.1 or to the core part of JScript, but without the navigator specific extensions. (download)

NJS is an independent implementation of the JavaScript language. It used to be called the NGS JavaScript Interpreter, but New Generation Software, the Finnish company who created it, is no longer developing the interpreter. However, due to their choice of license (the GNU LGPL), development has continued. Also, the name NJS was chosen as the old name clashed with both the Linux joystick calibration utility (called obviously enough, js) and the Mozilla shared library of their JavaScript engine. (download)


Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.
This Mozilla compiler translates JavaScript source into Java class files. The resulting Java class files can then be loaded and executed at another time, providing a convenient method for transfering JavaScript, and for avoiding translation cost. (download)

8. Projects and Software in JavaScript  (^)



9. Standard  (^)

JavaScript is the originating implementation of the ECMAScript standard.
ECMAScript is a scripting programming language, standardized by Ecma International in the ECMA-262 specification. The language is widely used on the web, and is often referred to as JavaScript or JScript, after the two primary implementations of the specification.

10. References  (^)

[1] JavaScript @ wikipedia.org
[2] JavaScript syntax @ wikipedia.org
[3] Mozilla's Official Documentation on JavaScript
[4] Converting Strings to Numbers in JavaScript
[5] JavaScript Functions
[6] Some tasks written in JavaScript