ECMAScript

Appeared in:
1995
Influenced by:
Influenced:
Paradigm:
Typing discipline:
File extensions:
.es
Dialects:
Versions and implementations (Collapse all | Expand all):
Programming language

ECMAScript is a scripting language standard, implemented and used as its dialects.

ECMAScript was created as a standardized version of JavaScript, so the latter appeared in 1996, but the first standard for the former was published in 1997, giving the language its name and identity.

The standard for ECMAScript is developed by Ecma International and is given in specification ECMA-262, which had several editions, first one published in June 1997, last one (as of December 2009) — in December 2009.

ECMAScript is implemented in the form of its dialects, most popular of which are JavaScript and ActionScript. JavaScript is the most popular scripting language for client-side part of web-applications, and thus usually integrated in a web-browser, though JavaScript interpreters are often embedded in non-web-oriented tools. ActionScript is the programming language used mostly in for Adobe Flash.

ECMAScript is a relatively new language, so it contains features borrowed from a lot of older ones.

Elements of syntax:

Inline comments //
Nestable comments /* */
Case-sensitivity Yes
Variable assignment <varname> = <value>
Variable declaration var <varname>[,<varname2>, ...]
Variable declaration with assignment var <varname> = <value>
Grouping expressions ( )
Block { }
Physical (shallow) equality ==
Physical (shallow) inequality !=
Deep equality ===
Deep inequality !==
Comparison < > <= >=
Function definition function <functionname>()

Examples:

Factorial:

Example for versions SpiderMonkey 1.7

This example uses recursive factorial definition and is meant to be executed from the web-browser. To run the example, copy its source text to a file factorial.js and create an HTML file placed in the same directory and containing the following text:

<head><script type="text/javascript" src="factorial.js"></script></head> <body></body>

When you open the HTML file, JavaScript code runs and writes its output to the page shown. document.clear() command clears everything that is written on the currrent web-page.

function factorial(n)
{   if (n == 0)
        return 1;
    else
        return n * factorial(n-1);
}
var i;
document.clear();
for (i = 0; i <= 16; i++)
    document.write(i + "! = " + factorial(i) + "<br />");

Fibonacci numbers:

Example for versions SpiderMonkey 1.7

This example uses recursive definition of Fibonacci numbers and is meant to be executed from web-browser.

function fibonacci(n)
{   if (n<3)
        return 1;
    else
        return fibonacci(n-1) + fibonacci(n-2);
}
var i;
document.clear();
for (i = 1; i <= 16; i++)
    document.write(fibonacci(i) + ", ");
document.write("...<br />");

Quadratic equation:

Example for versions SpiderMonkey 1.7

The example is meant to be executed from the web-browser. To run the example, copy the code to a file quadratic.js and create an HTML file placed in the same directory and containing the following text:

<head>
<script type="text/javascript" src="quadratic.js"></script>
</head>
<body>
<form name="quadratic">
    <input type="number" required="required" name="A">
    <input type="number" required="required" name="B">
    <input type="number" required="required" name="C">
    <input type="button" value="Solve" onClick="solve()">
</form>
<p id="output">
</p>
</body>

This will create a web-page with three input fields and a button. The equation will be solved once the button is pressed, and the roots will be printed beneath the inputs.

JavaScript doesn’t provide complex numbers, so the calculations are done in real numbers with separate check for discriminant sign. This implementation allows to solve quadratic equations not only with integer coefficients but also with floating-point ones.

function print(real, imag) 
{   if (Math.abs(imag)<1E-6)
        return real;
    else
        return '('+real+','+imag+')';
}

function solve() 
{   A = document.quadratic.A.value;
    if (Math.abs(A)<1E-3)
    {   document.getElementById('output').innerHTML = 'Not a quadratic equation';
        return;
    }
    B = document.quadratic.B.value;
    C = document.quadratic.C.value;
    A = 2*A;
    D = B*B-2*A*C;
    if (Math.abs(D)<1E-3)
    {   document.getElementById('output').innerHTML = 'x = '+(-B/A);
        return;
    }
    if (D>0)
        document.getElementById('output').innerHTML = 'x1 = '+print((-B+Math.sqrt(D))/A, 0)+'<br />x2 = '+print((-B-Math.sqrt(D))/A, 0);
    else
        document.getElementById('output').innerHTML = 'x1 = '+print(-B/A,Math.sqrt(-D)/A)+'<br />x2 = '+print(-B/A,-Math.sqrt(-D)/A);
}

Hello, World!:

Example for versions Rhino 1.6, SpiderMonkey 1.7

JavaScript uses different commands to output messages depending on what environment is it used in:

  • print: for interpreters with command-line interface prints the message to standard output stream, but when used in web-browser, calls print dialog instead;
  • document.write: when used in web-browser, prints the message to the current document (web-page);
  • console.log: a command for Firebug plugin which prints the message to debug console of the plugin;
  • alert: when used in web-browser, creates a pop-up information window with the message.

Note that three last commands won’t work in non-browser-based environment, since they use objects (document and console) which are not defined in command-line interfaces.

The example itself works in a smart universal way: since it can be executed in multiple environments with various objects defined, it checks each object in turn, and uses the first available writing method.

if (typeof console === 'object') {
    console.log('Hello, World!');
} else if (typeof document === 'object') {
    document.write('Hello, World!');
} else {
    print('Hello, World!');
}

CamelCase:

Example for versions SpiderMonkey 1.7

This example is meant to be executed from web-browser, same as quadratic equation. Input form should look like this:

<form name="CamelCase">
  <input type="text" required="required" name="txt">
  <input type="button" value="Convert to CamelCase" onClick="convert()">
</form>

The code itself could have been written in one line, but has been broken in several parts for better readability. First line gets the string to process; second line converts it to lower case and replaces all non-letter characters with spaces; third line capitalizes each word; and fourth line removes all spaces. JavaScript has a very strong support of regular expressions, so this is done easily.

function convert() {
  txt = document.CamelCase.txt.value;
  txt = txt.toLowerCase().replace(/[^a-z ]+/g, ' ');
  txt = txt.replace(/^(.)|\s(.)/g, function($1) { return $1.toUpperCase(); });
  txt = txt.replace(/[^a-zA-Z]+/g, '');
  document.getElementById('output').innerHTML = txt;
}

Hello, World!:

Example for versions Adobe Flex 3.4

While the constructor Main() is called first, it contains a small routine that causes initialization to occurr only if it is created on a stage or when it is added to a stage.

“Hello World” is created via a TextField object.

package 
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.display.MovieClip;
	import flash.text.TextField;
	
	public class Main extends Sprite 
	{
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);

			// entry point		
			var tf:TextField = new TextField();
			tf.text = "Hello World!";
			tf.x = 200;
			tf.y = 20;
			this.addChild(tf);
		}
	}
}

Quadratic equation:

Example for versions Adobe Flex 3.4

When Main() is called, it contains a small routing to initialize the text fields and display labels.

The example is constructed from four text fields, not counting the clickable button or static text. It takes input from three editable text fields (identified by TextFieldType.INPUT), and places the result in the output text field.

The example may be modified to update the result instantly, but this one requires clicking “Calculate” to get the result.

package 
{
	import flash.display.SimpleButton;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextField;
	import flash.text.TextFieldType;
	
	/**
	 * ...
	 * @author Raymond Martineau
	 */
	public class Main extends Sprite 
	{
		var tf_a:TextField;
		var tf_b:TextField;
		var tf_c:TextField;
		var tf_result:TextField;
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}

		/**
		 * This function initializes the display elements. 
		 */
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			
			// entry point
			tf_a = new TextField();
			tf_a.text = "1";
			tf_a.x = 40;
			tf_a.y = 10;
			tf_a.height = 20;
			tf_a.type = TextFieldType.INPUT;
			tf_a.border = true;
			this.addChild(tf_a);
		
			
			tf_b = new TextField();
			tf_b.text = "1";
			tf_b.x = 40;
			tf_b.y = 30;
			tf_b.height = 20;
			tf_b.type = TextFieldType.INPUT;
			tf_b.border = true;
			this.addChild(tf_b);
			
			tf_c = new TextField();
			tf_c.text = "0";
			tf_c.x = 40;
			tf_c.y = 50;
			tf_c.height = 20;
			tf_c.type = TextFieldType.INPUT;
			tf_c.border = true;
			this.addChild(tf_c);

			/** 
			 * If desired, you could add the following line to update
			 * the calculation whenever the value is changed
			 * 
			 *   tf_a.addEventListener(Event.CHANGE, changed);
			 *   tf_b.addEventListener(Event.CHANGE, changed);
			 *   tf_c.addEventListener(Event.CHANGE, changed);
			 * 
			 * In this example, it's activated by clicking the calculate button.
			 */
			
			var tf:TextField;
			tf = new TextField();
			tf.text = "A = ";
			tf.x = 10;
			tf.y = 10;
			tf.width = 29;
			tf.height = 20;
			tf.borderColor = 255;
			this.addChild(tf);
			
			tf = new TextField();
			tf.text = "B = ";
			tf.x = 10;
			tf.y = 30;
			tf.width = 29;
			tf.height = 20;
			this.addChild(tf);

			tf = new TextField();
			tf.text = "C = ";
			tf.x = 10;
			tf.y = 50;
			tf.width = 29;
			tf.height = 20;
			this.addChild(tf);

			var btn:TextField = new TextField();
			btn.x = 40
			btn.y = 80
			btn.width = 80
			btn.height = 20
			btn.text = "Calculate"
			btn.border = true;
			btn.backgroundColor = 0xcccccc;
			btn.background = true;
			btn.selectable = false;
			this.addChild(btn);			
			
			btn.addEventListener(MouseEvent.CLICK, changed);
			
			tf_result = new TextField();
			tf_result.x = 10;
			tf_result.y = 110;
			tf_result.width = 400;
			this.addChild(tf_result);

			updateResult();
		}

		private function changed(e:Event = null)
		{
			updateResult();
		}
		
		private function updateResult()
		{
			var a:Number, b:Number, c:Number, d:Number;
			a = Number(tf_a.text); b = Number(tf_b.text); c = Number(tf_c.text);
			
			d = b * b - 4 * a * c;
			if (a == 0)
			{
				tf_result.text = "Not a quadratic equation";
			}
			else if (d == 0)
			{
				tf_result.text = "One root: " + ( -b / (2 * a));
			}
			else if (d>0)
			{
				tf_result.text = "Two roots: " + (( -b + Math.sqrt(d)) / (2*a)) + ", " + (( -b - Math.sqrt(d)) / (2*a));
			} else if (d < 0)
			{
				var e:Number = -b / 2 * a;
				var f:Number = Math.sqrt( -d) / 2 * a;
				if (f < 0) f = -f;
				tf_result.text = "Two roots: (" + e + ", " + f + "), (" + e + " - " + f + ")";
			}
			
			return 0; 
		}
		
	}
	
}