A function is a segment of ECMAScript code that can be called from other parts of a ECMAScript program. Functions are declared using the function keyword, for example:
function square(x){ return x*x; }
This function, which returns the square of a number, can be called as follows:
var y = square(4);
If the caller passes a built-in type to a function, it is passed by value. If the caller passes an object, it is passed by reference. A function can be made to return an object as well. The members of the object can be dynamically declared before the object is returned, for example:
function Employee(firstName, lastName, age){ this.firstName = firstName; this.lastName = lastName; this.age = age; return this; }
This function can be used to construct new Employee objects:
var employee1 = new Employee("John", "Smith", 35);
That object can then be accessed using the membership operator (.):
var fullname = employee1.firstName + " " + employee.lastName;
An important object that comes as a part of ECMAScript is the Array. ECMAScript arrays can be declared as follows:
var a = new Array();
This array can be populated, for example:
a[0] = "Zero"; a[1] = "One";
An array automatically resizes itself based on how it is populated. For example:
a[10] = "Ten";
This causes the array a to resize to 11 elements. The uninitialized elements will have a value of null.
An array can also be string-indexed. Instead of using numbers as indexes, you can use strings, for example:
var capitals = new Array(); capitals["New York"] = "Albany"; capitals["France"] = "Paris"; capitals["China"] = "Beijing";
This array can be accessed as follows:
var c = capitals["China"];
3.135.205.172